vette982
vette982

Reputation: 4870

sizeof an inline struct declaration

If there's a structure with a pointer to a struct declared within it, how do you determine the size of the sub-struct?

typedef struct myStruct {
  int member;
  struct subStruct {
    int a;
    int b;
  } *subStruct_t;
} myStruct_t;

How do you allocate space for the subStruct_t pointer? I was thinking something along the lines of

myStruct_t M;
M.subStruct_t = calloc(1,sizeof(myStruct_t.subStruct_t);

but it obviously doesn't work. Any ideas?

Upvotes: 2

Views: 744

Answers (5)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

One technique that's sometimes useful (e.g. in macros that take the type as an argument):

sizeof(*((struct myStruct *)0)->subStruct_t);

I'm not 100% sure but I believe this is legal since the operand of sizeof is not actually evaluated.

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96258

M.subStruct_t = calloc(1,sizeof(*M.subStruct_t));

Note: allocate for the size of the structure, not for the pointer

Upvotes: 7

Adam Rosenfield
Adam Rosenfield

Reputation: 400146

In C, inner structs get placed in the global namespace, so you can simply use sizeof(struct subStruct). In C++, you have to use the scope resolution operator ::, so you would instead say sizeof(myStruct::subStruct).

You can also just use the name of the dereferenced variable -- the operands to sizeof are not evaluated -- so sizeof(*M.subStruct_t) would also work.

One piece of advice: do not name your struct member with the _t suffix. The _t suffix should be used for types, not for variables/members. Furthermore, POSIX reserves all identifiers with the _t suffix (see section 2.2.2 of the POSIX.1-2008 spec), so you should not name your own types with _t.

Upvotes: 4

john
john

Reputation: 87944

In C++

myStruct_t M;
M.subStruct_t = (myStruct_t::subStruct*)calloc(1,sizeof(myStruct_t::subStruct));

I really wouldn't name variables or data members as subStruct_t, the _t convention is used for types.

Upvotes: 1

Tobias Schlegel
Tobias Schlegel

Reputation: 3970

if you're using c++, you should not use the typedef-syntax, but more cleanly:

struct myStruct_t {
  int member;
  struct subStruct_t {
    int a;
    int b;
  };

  subStruct_t* subStruct;
};

then you can get the size with:

sizeof(myStruct_t::subStruct_t);

Upvotes: 2

Related Questions