gpt4 book ai didi

c - 初始化 Malloc 结构

转载 作者:太空狗 更新时间:2023-10-29 15:21:44 25 4
gpt4 key购买 nike

我正在尝试使用大括号初始化结构,但我实际上是在尝试初始化从 malloc 调用返回的指针所指向的结构。

typedef struct foo{
int x;
int y;
} foo;

foo bar = {5,6};

我知道该怎么做,但我需要在这种情况下这样做。

foo * bar = malloc(sizeof(foo));
*bar = {3,4};

最佳答案

(这在评论中得到了回答,因此将其设为 CW)。

您需要转换赋值的右侧,如下所示:

*bar = (foo) {3,4};

正如@cremno 在评论中指出的,这不是强制转换,而是复合文字的赋值

C99 标准的相关部分是:6.5.2.5 Compound literals 其中说:

A postfix expression that consists of a parenthesized type name followed by a brace enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list

关于c - 初始化 Malloc 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31442927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com