繁体   English   中英

数组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};是否应该正确初始化students[0] = {.name = "John", .grade = 10}; ?。 以这种方式进行初始化时: struct Student s = {.name = "Joe", .grade = 10}; 然后将其设置为像students[1] = s;这样的数组students[1] = s; 我没有错误。 只是一个假设,但可能是{.name = "Joe", .grade = 10}表达式在内存中没有引用,并且结构数组仅仅是对已初始化结构的引用数组?

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

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

话虽如此,即使语法有点笨拙(IMO),也有一种解决方法,那就是使用复合文字创建一个临时的伪结构对象,并将其复制到变量中:

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}
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM