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?
M.subStruct_t = calloc(1,sizeof(*M.subStruct_t));
Note: allocate for the size of the structure, not for the pointer
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With