在数组内部初始化结构

时间:2019-07-24 05:55:24

标签: c struct

最近,我尝试了以下方法,作为初始化新结构并将其作为数组的第一个元素的快捷方式:

#include <stdio.h>

#define MAX_CARS 100

typedef struct car {
    int wheels;
    int cylinders;
    int maxSpeed;
    int canOffroad;
} Car;

int main(void) {
    Car all_cars[MAX_CARS];
    // This is nice, I would like to do something equivalent to this
    all_cars[0] = {.wheels = 4,
                   .cylinders = 8,
                   .maxSpeed = 120,
                   .canOffroad = 0};

    return 0;
}

但是,这会引发编译器错误,表示它期望在'{'之前有一个表达式。

现在,起初我以为我可能误记了初始化结构,但这行得通:

#include <stdio.h>

#define MAX_CARS 100

typedef struct car {
    int wheels;
    int cylinders;
    int maxSpeed;
    int canOffroad;
} Car;

int main(void) {
    Car all_cars[MAX_CARS];
    // This is ok, but introduces a (potentially) unnecessary variable
    Car new_car = {.wheels = 4,
                   .cylinders = 8,
                   .maxSpeed = 120,
                   .canOffroad = 0};
    all_cars[0] = new_car;

    return 0;
}

因此,问题显然在于将这种结构初始化为数组的元素而不是变量。

是否存在允许初始化这样的结构的语法,还是我每次想向数组中添加一个结构变量时都要坚持初始化?

1 个答案:

答案 0 :(得分:3)

问题是您试图初始化数组中的元素,这只有在定义数组时才可能。

只有在定义时才能进行初始化。

不过,您可以使用compound literals创建一个临时结构对象,然后将其复制到数组元素中:

all_cars[0] = (Car) {.wheels = 4,
                     .cylinders = 8,
                     .maxSpeed = 120,
                     .canOffroad = 0};