简体   繁体   English

结构尺寸(单位:C)

[英]structure size in C

      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 }

Output: 输出:

size of struct is: 20

Why int a[0] is not considered? 为什么不考虑int a[0]

I tried: 我试过了:

  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 }

And output: 并输出:

size of struct is: 0

a[0] is a member of structure. a[0]是结构的成员。 Then how come it is not considered in the size of structure? 那么,为什么不考虑结构的大小呢?

This is actually more complicated that it may look in the first place. 实际上,这实际上更复杂,以至于它看起来可能没有。

First of all, a member int a[0] is a constraint violation ("syntax error") in standard C. You must encounter an extension that is provided by your compiler. 首先,成员int a[0]是标准C中的约束违例(“语法错误”)。您必须遇到编译器提供的扩展名。

Arrays of zero size had often be used by pre-C99 compilers to emulate the effect of flexible array members , that have the syntax int a[] without bounds as the last member of a struct . C99之前的编译器经常使用零大小的数组来模拟灵活数组成员的效果,这些成员的语法int a[]无限制地作为struct的最后一个成员。

For the size of the whole struct , such an array doesn't count by itself, but it may impose alignment constraints. 对于整个struct的大小,这样的数组本身并不计数,但是可能会施加对齐约束。 In particular, it might add padding to the end of the other part of the structure. 特别是,它可能会在结构的其他部分的末尾添加填充。 If you'd do the same test for 如果您要进行相同的测试

struct toto {
   char name[3];
   double a[];
};

(with [0] if your compiler needs it), you most probable see a size of 4 or 8 for it, since these are the usually alignment requirements for double . (如果编译器需要[0]则为[0] ),您最有可能看到48的大小,因为这些通常是double对齐要求。

Now try this: 现在尝试这个:

 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)==sizeof(t.a));
 11     return 0;
 12 }

If you have no money in your bank account you don't have money at all :) 如果您的银行帐户中没有钱,那么您根本就没有钱:)

元素为零的array的大小为0可以使用sizeof(a[0])进行检查。因此不考虑结构的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM