gpt4 book ai didi

c - C中的结构大小

转载 作者:太空宇宙 更新时间:2023-11-04 01:10:50 25 4
gpt4 key购买 nike

      1 #include <stdio.h>
2
3
4 struct test {
5 char c;
6 int i;
7 double d;
8 void *p;
9 int a[0];
10 };
11
12 int main (void) {
13 struct test t;
14 printf("size of struct is: %d\n", sizeof(t));
15 return 0;
16 }

输出:

size of struct is: 20

为什么不考虑int a[0]

我试过:

  1 #include <stdio.h>
2
3
4 struct test {
5 int a[0];
6 };
7
8 int main (void) {
9 struct test t;
10 printf("size of struct is: %d\n", sizeof(t));
11 return 0;
12 }

并输出:

size of struct is: 0

a[0] 是结构的成员。那怎么在结构尺寸上没有考虑呢?

最佳答案

这实际上比最初看起来更复杂。

首先,成员 int a[0] 在标准 C 中是约束违规(“语法错误”)。您必须遇到编译器提供的扩展。

C99 之前的编译器经常使用零大小的数组来模拟灵活数组成员的效果,这些成员的语法 int a[] 没有边界作为struct 的最后一个成员。

对于整个struct的大小,这样的数组本身并不算数,但它可能会施加对齐约束。特别是,它可能会在结构的其他部分的末尾添加填充。如果你对

做同样的测试
struct toto {
char name[3];
double a[];
};

(使用 [0] 如果您的编译器需要它),您最有可能看到它的大小为 48,因为这些通常是 double 的对齐要求。

关于c - C中的结构大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12721760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com