2014-05-23 31 views
1

N.B:这与Effects of __attribute__((packed)) on nested array of structures?嵌套结构数组的大小是如何决定的?

类似但不完全相同我正在定义一个包含多个嵌套结构的结构类型。 其中一个成员是一堆包装结构,这让我对它应该嵌套的顺序有些困惑,相对于先有较大成员的规范。

如果该成员是一个长度为4的8个字节的结构数组,则该成员总数为32个字节,被视为用于打包和对齐的单一实体,从而使另一个单个结构成员18字节,实际上更小?

e.g

typedef struct __attribute__((__packed__)) settingsProfile { 
/* For packing and alignment, is this member 32 bytes or 4 'chunks'(?) of 8 bytes?*/ 
    struct __attribute__((__packed__)) load { 
     int32_t slewRate; 
     int32_t current; 
    } load[4]; 

/* 18 bytes, so if the above *isn't* 32 it should be below this */ 
    struct __attribute__((__packed__)) ac { 
     int32_t slewRate; 
     int32_t voltage; 
     int32_t iLimit; 
     int32_t ovp; 
     bool dcMode; 
    }; 

    struct __attribute__((__packed__)) xfmr {  // 4 bytes 
     int32_t ocp; 
    } xfmr; 
    uint16_t extOtp[2];      // 4 bytes 
} settingsProfile_t; 

谢谢!

+1

请记住,在您使用的类型中,数字是位数。所以对于'int32_t',它是一个32位整数,32位是4个字节。这意味着两个'int32_t'成员的结构将是8个字节,并且在这些结构的四个数组中,您有8 * 4(32)个字节。这意味着你所有的手动尺寸计算都是错误的。 –

+0

哦拍!我在实际的代码中使用WORDS语言,在写这里的时候忘了加倍大小,现在更新ta。 – Toby

回答

1

struct是一种不是一个变量:

... 
/* 18 bytes, so if the above *isn't* 32 it should be below this */ 
    struct __attribute__((__packed__)) ac { 
     int32_t slewRate; 
     int32_t voltage; 
     int32_t iLimit; 
     int32_t ovp; 
     bool dcMode; 
    }; 
... 

所以它的大小将不会被包含在sizeof(settingsProfile_t)

你可能在寻找:

typedef struct __attribute__((__packed__)) settingsProfile { 
    uint16_t extOtp[2];      // 4 bytes 
    struct __attribute__((__packed__)) xfmr {  // 4 bytes 
     int32_t ocp; 
    } xfmr; 

    // total 17 
    struct __attribute__((__packed__)) ac { 
     int32_t slewRate;      // 4 
     int32_t voltage;       // 4 
     int32_t iLimit;       // 4 
     int32_t ovp;        // 4 
     bool dcMode;       // 1 
    } foo; // << ***here*** 

    // total 32 
    struct __attribute__((__packed__)) load { 
     int32_t slewRate;      // 4 
     int32_t current;       // 4 
    } load[4]; 

} settingsProfile_t; 

在我的编译器总sizeof(settingsProfile_t)。如数字解释,是57