长度为零的数组

From User's Guide to GNU C++
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 standard C, you would have to give contents a length of 1, which means either you waste space or complicate the argument to malloc.

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
解析:
长度为零的数组的想法源于C语言——试图说明一个可变长的struct。在上面的例子里,struct line的大小,对编译器来说,为四字节(类型为int的字段length的长度)。但是,你可以动态分配,例如200字节的一个内存块(类型为char[200]),再把这个块的指针,cast成类型为struct line的指针。这样,在这个struct line的变量中,字段contents就可以视为一个长度为196个元素的char数组来使用了。

这种做法的优点是,比起把contents说明成char的指针,效率要高。因为访问contents的元素时,不需要间接访问了。

这种做法的缺点是不安全,特别是释放这个块(200字节)时,要你“人工”干预。因为编译器认为,这个由struct line的指针指向的块,只有4个字节。即你不应该去释放struct line,而是应该直接去释放最开始动态分配的那200个字节的内存块。

然而,在C++语言里,是不允许零长数组的(摘自pp137,C++标准ISO/IEC-14882(2003)E )

因此,GNU C++这个“feature”,是不可移植的,还是不用为妙(或者数组长度的长度至少要为1)。


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
posted @ 2009-09-05 23:22  芈希有  阅读(913)  评论(0编辑  收藏  举报