C结构类型令人困惑
struct payload{
struct metadata meta;
char data_pointer[0];
};
struct payload* mypayload = (struct payload*) malloc(sizeof(struct payload) + 50);
这里的mypayload类型是什么? 地址,指针或其他东西
struct payload{
struct metadata meta;
char data_pointer[0];
};
struct payload* mypayload = (struct payload*) malloc(sizeof(struct payload) + 50);
What is the type of mypayload here?
The address, pointer, or something else
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
malloc
返回一块未型的内存,分配是您告诉编译器是什么类型的方式。在这种情况下,struct有效载荷 *
是内存的指针(地址),如果分配失败,则分配或null。您不需要Cast
(struct Poreload*)
。如果要
data_pointer
是灵活的数组成员,则将大小未指定的char data_pointer [];
留下。大小0
的数组是未定义的行为。malloc
returns an untyped chunk of memory, and the assignment is how you tell the compiler what type it is. In this casestruct payload *
which is a pointer (an address) of the memory that was allocated or NULL if the allocation failed.You don't need the cast
(struct payload*)
.If you want
data_pointer
to be a flexible array member, then you leave the size unspecifiedchar data_pointer[];
. An array of size0
is undefined behavior.mypayload
是指针,是struct> struct有效载荷
的指针。 @kaylum,例如
char data_pointer [0];
未由C定义,尽管某些实现使其作为灵活数组成员(fam)。由于C99使用
char data_pointer [];
将 last 成员定义为A 灵活数组成员。要最好分配a 灵活数组成员,请计算2个尺寸的总和:
size of mypayload [0]
:对象的大小到达但不包括FAM成员。这将包括FAM成员面前的任何填充。mypayload-> data_pointer [0]
:所需数组元素的数量50的FAM的大小。提示:在
sizeof
代码中不需要A 类型。易于正确编码,查看和维护以使用引用对象的大小。提示:不需要。
提示:检查分配成功。
例子:
mypayload
is a pointer, a pointer to astruct payload
. @kaylumA
struct
array member with size 0, likechar data_pointer[0];
is not defined by C although some implementations had allowed it as a pre-cursor to a flexible array member (FAM).Since C99 use
char data_pointer[];
to define the last member as a flexible array member.To best allocate for a flexible array member, compute the sum of 2 sizes:
sizeof mypayload[0]
: Size of the object up to, but not including the FAM member. This will include any padding before the FAM member.sizeof mypayload->data_pointer[0]
: Size of the FAM referenced data times the count, 50, of array elements desired.Tip: a type is not needed in the
sizeof
code. Easier to code right, review and maintain to use the size of the referenced object.Tip: Cast not needed.
Tip: Check for allocation success.
Example:
mypayload
是指针。这是通过malloc()
分配的内存的指针。并且您将其配置为指向有效载荷
的指针。mypayload
is a pointer. It's a pointer to the memory allocated bymalloc()
. And you have it configured as a pointer to apayload
.