数组 C 中的结构初始化行为

Struct initialization behaviour in arrays C

我在文件 test.c 中有这段简单的代码:

#include <stdio.h>
#include <string.h>

struct Student {
    char name[10];
    int grade;
};

int main(){

    struct Student s = {.name = "Joe", .grade = 10}; //correct

    struct Student students[10];

    students[0] = {.name = "John", .grade = 10}; //error

    students[1] = s; //correct

    struct Student some_other_students[] = {
        {.name = "John", .grade = 10}
    }; //correct

    students[2].grade = 8;
    strcpy(students[2].name, "Billy"); //correct?!? O_o


    return 0;
}

编译时出现此错误

test.c|14|error: expected expression before '{' token|

数组不应该在 students[0] = {.name = "John", .grade = 10}; 处正确初始化吗?。以这种方式初始化时: struct Student s = {.name = "Joe", .grade = 10}; 然后将其设置为这样的数组 students[1] = s; 我没有收到任何错误。只是一个假设,但可能是 {.name = "Joe", .grade = 10} 表达式在内存中没有引用,而结构数组只是对已初始化结构的引用数组?

但是话又说回来,如果数组只是初始化结构的引用,这又如何工作? students[2].grade = 8;?

您只能在 定义 变量时对其进行初始化。定义变量后,当您 分配 给变量时,您不能使用与用于初始化时相同的语法。您尝试分配给数组元素并不重要,重要的是您使用分配而不是初始化。

话虽如此,即使语法有点笨拙(IMO),也有办法解决这个问题,那就是使用 compound literals 创建一个临时的虚拟结构对象,并将其复制到变量:

students[0] = (struct Student){.name = "John", .grade = 10};

以上相当于

{
    // Define and initialize a "temporary" Student structure object
    struct Student temp = {.name = "John", .grade = 10};

    // Assign it to students[0]
    students[0] = temp;
}

或者您可以在 定义 时初始化数组:

struct Student students[10] = {
    {.name = "John", .grade = 10}
};