sizeof single struct member in C sizeof single struct member in C c c

sizeof single struct member in C


Although defining the buffer size with a #define is one idiomatic way to do it, another would be to use a macro like this:

#define member_size(type, member) sizeof(((type *)0)->member)

and use it like this:

typedef struct{    float calc;    char text[255];    int used;} Parent;typedef struct{    char flag;    char text[member_size(Parent, text)];    int used;} Child;

I'm actually a bit surprised that sizeof((type *)0)->member) is even allowed as a constant expression. Cool stuff.


I am not on my development machine right now, but I think you can do one of the following:

sizeof(((parent_t *)0)->text)sizeof(((parent_t){0}).text)


Edit: I like the member_size macro Joey suggested using this technique, I think I would use that.


Use a preprocessor directive, i.e. #define:

#define TEXT_LEN 255typedef struct _parent{  float calc ;  char text[TEXT_LEN] ;  int used ;} parent_t ;typedef struct _child{  char flag ;  char text[TEXT_LEN] ;  int used ;} child_t ;