sizeof single struct member in C

后端 未结 9 2224
礼貌的吻别
礼貌的吻别 2020-11-30 17:13

I am trying to declare a struct that is dependent upon another struct. I want to use sizeof to be safe/pedantic.

typedef struct _parent
{
  floa         


        
9条回答
  •  执念已碎
    2020-11-30 17:52

    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.

提交回复
热议问题