在gnu c中有一种用法,就是可以使用长度为0的数组,比如说一下这个结构体:

struct sample {

int length;

char store[0];

}

可以像以下这种方式来使用:

struct sample * example = (struct sample *)malloc(sizeof(struct sample)+size);

example->length = size;

example->store = example + sizeof(struct sample);

 

这个方法的优势主要在于你可以在结构体中分配不定长的大小,当然有些人肯定会说,在结构体中不适用这种奇葩的数组,而使用指针不是一样的么?我们可以比较一下:

 

假设结构体的定义为

struct sample {

int length;

char * store;

}

则使用方式变成

struct sample * example = (struct sample *)malloc(sizeof(struct sample));

example->length = size;

example->store =(char *)malloc(size);

 

而释放内存时,使用长度0的数组释放是:

free(example);

而指针方式则

free(example->store);

free(example);

 

从上面的比较可以看书,使用长度为0的数组可以达到更简单的效果,同时节省了空间,因为使用长度为0的数组对应的结构体的长度为4(0数组不占空间),而指针的结构体对应的长度为8。