c中的sizeof初始化常量
我编写了简单的示例代码(也可以在 ideone 上找到)来显示我发现问题的地方。Sizeof 在常量的情况下返回错误的结果s。波纹管是文件main.c。
#include <stdint.h>
#include <stdio.h>
// comment this option if you know what is UB and want to avoit it
#define I_DONT_KNOW_WHAT_IS_UB ( 1 )
struct _sa {
uint32_t w;
uint8_t const a[];
};
uint8_t const a[] = { 7,6,5,4,3,2,1,0 };
struct _sa const s = {
.w = 8,
.a = { 7,6,5,4,3,2,1,0 },
};
char const b[] = "line";
int main(void)
{
#ifdef I_DONT_KNOW_WHAT_IS_UB
printf("sizeof(a) = %d n", (int)sizeof(a)); // = 8
printf("sizeof(s) = %d n", (int)sizeof(s)); // = 4
printf("sizeof(b) = %d n", (int)sizeof(b)); // = 5
#else
printf("sizeof(a) = %zu n", sizeof(a)); // = 8
printf("sizeof(s) = %zu n", sizeof(s)); // = 4
printf("sizeof(b) = %zu n", sizeof(b)); // = 5
#endif
return 0;
}
我使用旧的 ubuntu:
uname -a
Linux imbearr 4.4.0-148-generic #174~14.04.1-Ubuntu SMP Thu May 9 08:17:37 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
gcc --version
gcc (Ubuntu 9.3.0-11ubuntu0~14.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
gcc main.c -o szof -Xlinker -Map=szof.map
grep -C 1 "bsb" ./szof.map
0x00000000004005e8 a
0x00000000004005f0 s
0x00000000004005fc b
所以我通过链接器映射文件检查了大小:0x4005fc - 0x4005f0 = 12, 0x4005f0 - 0x4005e8 = 8。
为什么我有这样的结果,这是gcc的限制还是错误,可能是我的错误?
回答
sizeof 返回参数类型的大小。
所以当你打电话时sizeof(b),你真的是在struct _sa问,“尺寸是多少? ”
的大小struct _sa为4个字节,因为element.w占用了4个字节,element.a是一个灵活的占用零字节的数组,因为type中定义的数组没有定义大小。