【发布时间】:2018-07-23 01:33:40
【问题描述】:
假设我们使用avr-gcc来编译具有以下结构的代码:
typedef struct {
uint8_t bLength;
uint8_t bDescriptorType;
int16_t wString[];
} S_string_descriptor;
我们像这样全局初始化它:
const S_string_descriptor sn_desc PROGMEM = {
1 + 1 + sizeof L"1234" - 2, 0x03, L"1234"
};
让我们检查一下它生成了什么:
000000ac <__trampolines_end>:
ac: 0a 03 fmul r16, r18
ae: 31 00 .word 0x0031 ; ????
b0: 32 00 .word 0x0032 ; ????
b2: 33 00 .word 0x0033 ; ????
b4: 34 00 .word 0x0034 ; ????
...
因此,确实字符串内容根据需要遵循结构的前两个元素。
但是如果我们尝试检查sizeof sn_desc,结果是2。
变量的定义是在编译时完成的,sizeof 也是一个编译时运算符。那么,为什么sizeof var 没有显示var 的真实大小?编译器的这种行为(即,将任意数据添加到结构中)记录在哪里?
【问题讨论】:
-
相关:why static initialization of flexible array member work。 C 标准规定,结构中的灵活数组成员不会增加结构的大小(除了可能在末尾添加一些填充),但 gcc 无论如何都允许您对其进行初始化。
-
@MarkPlotnick 请将此作为答案,以便我接受。