sizeof single struct member in C

后端 未结 9 2075
礼貌的吻别
礼貌的吻别 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 18:03

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

    #define TEXT_LEN 255
    
    typedef 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 ;
    
    0 讨论(0)
  • 2020-11-30 18:06

    c++ solution:

    sizeof(Type::member) seems to be working as well:

    struct Parent
    {
        float calc;
        char text[255];
        int used;
    };
    
    struct Child
    {
        char flag;
        char text[sizeof(Parent::text)];
        int used;
    };
    
    0 讨论(0)
  • 2020-11-30 18:06

    @joey-adams, thank you! I was searching the same thing, but for non char array and it works perfectly fine even this way:

    #define member_dim(type, member) sizeof(((type*)0)->member) / \
                                     sizeof(((type*)0)->member[0])
    
    struct parent {
            int array[20];
    };
    
    struct child {
            int array[member_dim(struct parent, array)];
    };
    
    int main ( void ) {
            return member_dim(struct child, array);
    }
    

    It returns 20 as expected.

    And, @brandon-horsley, this works good too:

    #define member_dim(type, member) sizeof(((type){0}).member) / \
                                     sizeof(((type){0}).member[0])
    
    0 讨论(0)
提交回复
热议问题