热门问题
时间线
聊天
视角

灵活数组类型

来自维基百科,自由的百科全书

Remove ads

灵活数组类型[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支持。

Remove ads

参考文献

Loading content...
Loading related searches...

Wikiwand - on

Seamless Wikipedia browsing. On steroids.

Remove ads