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

时间:2018-01-05 14:04:19

标签: c structure

我在文件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;

1 个答案:

答案 0 :(得分:4)

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

话虽如此,有一种解决方法,即使语法有点笨拙(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}
};