结构体类型T [1]中的最后一个成员,而不是T *
我看到我的项目中的下一个代码:
I saw next code in the project I work:
struct Str
{
size_t count;
T data[1];
};
Str* str = (Str*)malloc(sizeof(Str) + sizeof(T) * count);
str->count = count
...
str-> data
用作 count
的元素 T
为什么要声明 T data [1]
而不是 T * data
?这是否有什么好处?
Why one would declare T data[1]
instead of T* data
? Is there any benefit of doing this?
您的代码无效C ++。
Your code is not valid C++.
但是,它是有效的C,排序。在C中写这个的标准方法是声明最终成员为 T data [];
(一个柔性长度数组),目的是允许你请分配一个单一的动态内存块,并将一个固定的头和一个可变长度数组存储在一起。
However, it is valid C, sort of. The standard way of writing this in C is to declare the final member as T data[];
(a "flexible-length array"), and the purpose is to allow you do allocate one single dynamic chunk of memory and store both a fixed header and a variable-length array in it together.
使用这种类型有几个限制它不能是自动变量的类型或数组元素的类型)。例如,请参见 GCC实施,其中提供了几个非标准扩展。
There are several limitations to using such a type (e.g. it cannot be the type of an automatic variable, or of an array element). See for example the GCC implementation, which offers several non-standard extensions.