Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Syntax for accessing members of nested structures

Status
Not open for further replies.

xwb

Programmer
Jul 11, 2002
6,828
0
36
GB
I have a set of nested structures
Code:
struct Level1
{
   int m1one;
   int m1two;
   struct Level2
   {
      int m2one;
      int m2two;
   } mLevel2;
};
If I wish to use offsetof for m1two, the call is offsetof(Level1,m1two). Nice and simple.

In C++, if I wish to use offsetof for Level2.m2two, the call is offsetof(Level1::Level2,m2two). This doesn't work for C. How do you do it in C?
 
I found this article but it is not quite the same thing. It is suggesting

offsetof(Level1,mLevel2.m2two)

but it is not quite the same thing. I really would like the offset of m2two within mLevel2.

Not as elegant but I suppose I could use
Code:
offsetof(Level1, mLevel2.m2two) - offsetof(Level1,mLevel2)
 
Here are some examples, do these help?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

struct Level1
{
   int m1one;
   int m1two;
   struct Level2
   {
      int m2one;
      int m2two;
   } mLevel2;
};

int main ( ) {
  printf("%zd\n",offsetof(struct Level1,m1one));
  printf("%zd\n",offsetof(struct Level1,m1two));
  printf("%zd\n",offsetof(struct Level1,mLevel2));
  printf("%zd\n",offsetof(struct Level1,mLevel2)+offsetof(struct Level2,m2one));
  printf("%zd\n",offsetof(struct Level1,mLevel2)+offsetof(struct Level2,m2two));
  return 0;
}


$ gcc bar.c
$ ./a.out 
0
4
8
8
12

--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
The penny just dropped: I'm using a C interface and I need the word struct. It is fun going back to pure C: the simplest things catch you out. I had // as a comment and it took me a few minutes to work out what the compiler was complaining about.

offsetof(struct Level2,m2two) was what I was looking for.

BTW - what does %zd do? On Watcom, it just prints out zd!
 
'z' is the qualifier for C99 for printing size_t types.

Historically, cast the result to unsigned long and use %lu as the printf format.



--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top