C语言技巧之长度为0的数组
2013-04-10 23:53
477 查看
在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。
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。
相关文章推荐
- [C语言]除非该数组为全局变量,否则只能在定义数组时获取数组长度,在传递过程中只是传递指针不能再次获取长度
- 【c语言】数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字
- C语言中如何求任意一个int型数组的长度?
- (转载) C语言技巧:怎样把数组作为参数传递给函数?(值传递和指针传递)
- C语言零长度数组
- 长度为0的数组——C语言的非标准用法之一
- c语言中求数组的长度
- c语言中数组长度的计算
- 在结构体最后定义一个长度为0的字符数组(技巧)
- C语言中长度为0的数组
- C语言中如何不用STRLEN检测数组长度
- C语言获取数组长度示例
- 长度为0的数组的使用技巧
- C语言 可变长度的数组 -2
- 关于变长数组的一点小想法-C语言定义数组但是数组长度不确定怎么办
- Stream自行总结的技巧,如果设置一个字节数组接收一个未知长度的流Stream
- C语言中strlen求字符串长度,求字符数组长度(空字符,数字0,字符0,数组部分初始化)
- C语言中用什么方法可以检测数组长度
- C语言0长度数组(可变数组/柔性数组)详解
- C语言中用于计算数组长度的函数 “strlen() ”。