初始化 Malloc 结构

Initializing Malloc'ed structure

我正在尝试使用大括号初始化结构,但我实际上是在尝试初始化由 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

bar 是一个指向 malloced foo 结构的指针

使用bar->x=3;bar->y=4