Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof an inline struct declaration

Tags:

c++

c

memory

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?

like image 790
vette982 Avatar asked Sep 01 '26 23:09

vette982


2 Answers

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

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

like image 194
Karoly Horvath Avatar answered Sep 03 '26 13:09

Karoly Horvath


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.

like image 40
Adam Rosenfield Avatar answered Sep 03 '26 13:09

Adam Rosenfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!