结构体最后使用0或1的长度数组的原因,主要是为了方便的管理内存缓冲区,如果你直接使用指针而不使用数组,那么,你在分配内存缓冲区时,就必须分配结构体一次,然后再分配结构体内的指针一次,(而此时分配的内存已经与结构体的内存不连续了,所以要分别管理即申请和释放)而如果使用数组,那么只需要一次就可以全部分配出来,(见下面的例子),反过来,释放时也是一样,使用数组,一次释放,使用指针,得先释放结构体内的指针,再释放结构体。还不能颠倒次序。
其实就是分配一段连续的的内存,减少内存的碎片化。
看示例程序:
例1:test_size.c
10 struct tag1
20 {
30 int a;
40 int b;
50 }__attribute ((packed));
60
70 struct tag2
80 {
90 int a;
100 int b;
110 char *c;
120 }__attribute ((packed));
130
140 struct tag3
150 {
160 int a;
170 int b;
180 char c[0];
190 }__attribute ((packed));
200
210 struct tag4
220 {
230 int a;
240 int b;
250 char c[1];
260 }__attribute ((packed));
270
280 int main()
290 {
300 struct tag2 l_tag2;
310 struct tag3 l_tag3;
320 struct tag4 l_tag4;
330
340 memset(&l_tag2,0,sizeof(struct tag2));
350 memset(&l_tag3,0,sizeof(struct tag3));
360 memset(&l_tag4,0,sizeof(struct tag4));
370
380 printf("size of tag1 = %d/n",sizeof(struct tag1));
390 printf("size of tag2 = %d/n",sizeof(struct tag2));
400 printf("size of tag3 = %d/n",sizeof(struct tag3));
410
420 printf("l_tag2 = %p,&l_tag2.c = %p,l_tag2.c = %p/n",&l_tag2,&l_tag2.c,l_tag2.c);
430 printf("l_tag3 = %p,l_tag3.c = %p/n",&l_tag3,l_tag3.c);
440 printf("l_tag4 = %p,l_tag4.c = %p/n",&l_tag4,l_tag4.c);
450 exit(0);
460 }
__attribute ((packed)) 是为了强制不进行4字节对齐,这样比较容易说明问题。
程序的运行结果如下:
size of tag1 = 8
size of tag2 = 12
size of tag3 = 8
size of tag4 = 9
l_tag2 = 0xbffffad0,&l_tag2.c = 0xbffffad8,l_tag2.c = (nil)
l_tag3 = 0xbffffac8,l_tag3.c = 0xbffffad0
l_tag4 = 0xbffffabc,l_tag4.c = 0xbffffac4
从上面程序和运行结果可以看出:tag1本身包括两个32位整数,所以占了8个字节的空间。tag2包括了两个32位的整数,外加一个char *的指针,所以占了12个字节。tag3才是真正看出char c[0]和char *c的区别,char c[0]中的c并不是指针,是一个偏移量,这个偏移量指向的是a、b后面紧接着的空间,所以它其实并不占用任何空间。tag4更加补充说明了这一点。
Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure which is really a header for a variable-length object:
struct line { int length; char contents[0]; }; struct line *thisline = (struct line *) malloc (sizeof (struct line) + this_length); thisline->length = this_length;
In ISO C90, you would have to give contents
a length of 1, which means either you waste space or complicate the argument to malloc
.