灵活数组类型
灵活数组类型[1]是C99引入的语言特性。[2]即在struct
数据类型的最后一个数据成员,可以为一个未指明长度的数组类型。例如:
struct double_vector_st {
size_t length;
double array[]; // the flexible array member should be last
};
sizeof
运算符作用于这个struct
,返回灵活数组成员的偏移量。在堆上分配这种struct
,应该保留灵活数组的空间。如下例:
struct double_vector_st *allocate_double_vector(size_t len) {
struct double_vector_st *vec = malloc(sizeof *vec + len * sizeof vec->array[0]);
if (!vec) {
perror("malloc double_vector_st failed");
exit(EXIT_FAILURE);
}
vec->length = len;
for (size_t ix = 0; ix < len; ix++)
vec->array[ix] = 0.0;
return vec;
}
C++语言标准尚未支持灵活数组类型。但Visual C++2015支持。
参考文献
- . [2014-12-30]. (原始内容存档于2014-12-23).
- http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf (页面存档备份,存于) section §6.7.2.1, item 16, page 103
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.