0长度char数组的使用

来源:互联网 发布:佳能网络打印机驱动 编辑:程序博客网 时间:2024/06/05 12:12
需要引起注意的:ISO/IEC 9899-1999里面,这么写是非法的,这个仅仅是GNU C的扩展,gcc可以允许这一语法现象的存在。 
结构体最后使用0或1的长度数组的原因,主要是为了方便的管理内存缓冲区,如果你直接使用指针而不使用数组,那么,你在分配内存缓冲区时,就必须分配结构体一次,然后再分配结构体内的指针一次,(而此时分配的内存已经与结构体的内存不连续了,所以要分别管理即申请和释放)而如果使用数组,那么只需要一次就可以全部分配出来,(见下面的例子),反过来,释放时也是一样,使用数组,一次释放,使用指针,得先释放结构体内的指针,再释放结构体。还不能颠倒次序。
其实就是分配一段连续的的内存,减少内存的碎片化。
看示例程序:
例1:test_size.c
  struct tag1  {      int a;      int b;  }__attribute ((packed));   struct tag2  {      int a;      int b;      char *c;  }__attribute ((packed));  struct tag3  {      int a;      int b;      char c[0];  }__attribute ((packed));  struct tag4  {      int a;      int b;      char c[1];  }__attribute ((packed));  int main()  {      struct tag2 l_tag2;      struct tag3 l_tag3;      struct tag4 l_tag4;      memset(&l_tag2,0,sizeof(struct tag2));      memset(&l_tag3,0,sizeof(struct tag3));      memset(&l_tag4,0,sizeof(struct tag4));      printf("size of tag1 = %d/n",sizeof(struct tag1));      printf("size of tag2 = %d/n",sizeof(struct tag2));      printf("size of tag3 = %d/n",sizeof(struct tag3));      printf("l_tag2 = %p,&l_tag2.c = %p,l_tag2.c = %p/n",&l_tag2,&l_tag2.c,l_tag2.c);      printf("l_tag3 = %p,l_tag3.c = %p/n",&l_tag3,l_tag3.c);      printf("l_tag4 = %p,l_tag4.c = %p/n",&l_tag4,l_tag4.c);      exit(0);  }


__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