2012-10-04 78 views
1
 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]是结构的一个成员。那结构的大小怎么没有考虑呢?

+2

你期望'int a [0]'有多大? – glglgl

+0

只是一个疯狂的猜测 - 一个[0]是零元素的数组,声音逻辑大小为零。 –

+0

int a [0]将零整数存储在内存中。 – Nocturno

回答

1

现在试试这个:

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 } 

如果你没有钱在您的银行帐户,你没有钱在所有:)

0

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

4

这实际上比较复杂,它可能看起来首先。

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

阵列常常通过预C99编译器用于模拟的柔性阵列成员,具有语法int a[]无边界作为struct的最后一个成员的效果。

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

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

(与[0],如果你的编译器需要它),你最有可能看到的大小为48它,因为这些都是double平时对齐要求。