这是一个灵活的阵列结构成员用C呢? [英] Is this a Flexible Array Struct Members in C as well?
问题描述
可能重复:结果
灵活数组成员 - 坏
我阅读下列code:
struct hello {
int number;
int data[1];
};
我知道了灵活的数组成员让我们可以声明的最后一个元素是一个未指定大小的数组
是这样的:
struct hello {
int number;
int data[];
};
在此结构
,最后一个元素不指定大小,所以就是这两者之间的区别?又是什么第一个声明呢?
In this struct
, the last element does not specify the size, so what is the difference between these two? and what does the first declaration mean?
推荐答案
这类型的数组:
struct hello {
int number;
int data[];
};
不仅使结构感作为最后一个元素,只有当你从堆上分配结构,通常使头字段包含数组的实际大小:
only makes sense as last element of struct, and only when you allocate struct from heap, and typically so that header fields contain the real size of the array:
struct hello *helloptr = malloc(sizeof (struct hello) + count*(sizeof int));
helloptr->number = count;
使用是一个结构方便分配头和数据缓冲。
The use is to allocate header and data buffer conveniently with one struct.
另外:要你的版本,区别其分配大小为1的阵列,的sizeof结构你好
会更多,因为阵列与一个元素,而不是不确定的分配=零。这不是浪费一个项目价值的记忆,或使大小计算更复杂,是有点丑概念(你code的大小1阵列,当你真正的意思是不确定的,甚至可能是0)。
Addition: The difference to your version, which allocates array of size 1 is, sizeof struct hello
will be more, since array is allocated with one element instead undefined=zero. This either wastes one item worth of memory, or makes size calculations more complex, and is a bit "ugly" conceptually (your code has size 1 array, when you actually mean "undefined", possibly even 0).
在面向对象的C ++它更好地只是包装类中动态分配的缓冲区,这是怎么样的一个黑客真的。
In OOP C++ it's better to just wrap dynamically allocated buffer inside a class, this is kind of a "hack" really.
这篇关于这是一个灵活的阵列结构成员用C呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!