零长数组

Arrays of Length Zero

这样说:

Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure that is really a header for a variable-length object

零长数组在GNU C中是允许的。结构体中最后一个元素,把他用作变长对象的头。Flexible array 即柔性数组。

但是在C++中,C++约定每个对象在内存中有唯一的地址,故零长数组在C++中其实长度是1

struct line {
       int length;
       char contents[0];
};
struct line *thisline = (struct line *) malloc (sizeof (struct line) + this_length);
thisline->length = this_length;

可能会有疑问这里为何不直接搞一个指针和len即可?

如果用指针的话,这里不能保证变长对象的地址和结构体连续。这里就是柔性数组的好处。

内存的连续:

  • 提升访问速度
  • 方便释放
posted @ 2014-11-10 17:03  stevinwang  阅读(253)  评论(0编辑  收藏  举报