char c[1]的含义

看代码时候看到了,很土鳖的不知道是啥意思,总结下网上看到的内容。

需要引起注意的:ISO/IEC 9899-1999里面,这么写是非法的 ,这个仅仅是GNU C的扩展,gcc可以允许这一语法现象的存在。 

结构体最后使用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更加补充说明了这一点。


其实本质上涉及到的是一个C语言里面的数组和指针的区别问题,char a[1]里面的a和char *b的b相同吗? char a[1]里面的a实际是一个常量,等于&a[0]。而char *b是有一个实实在在的指针变量b存在。 所以,a=b是不允许的,而b=a是允许的。 两种变量都支持下标式的访问.

其实,这种语法是GCC对C语言做的扩展,官方权威说明在这里: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Zero-Length.html#Zero-Length

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值