简体   繁体   English

在C中初始化结构数组

[英]Initialising an array of structures in C

I'm doing a simple student database program exercise and I'm unsure of how to initialise an array of structures. 我正在做一个简单的学生数据库程序练习,我不确定如何初始化一组结构。 I'm trying to initialize the first 3 elements of the array stdt[] with values known at compile-time, and then the next 3 students' information will be populated from user input. 我正在尝试使用编译时已知的值初始化数组stdt[]的前3个元素,然后将从用户输入中填充接下来的3个学生的信息。 When I compile I get the error: 当我编译时,我收到错误:

lab7.c: In function ‘main’:

lab7.c:16:9: error: expected expression before ‘{’ token
 stdt[0]={"John","Bishop","s1234","Inf",'m',18};
         ^

lab7.c:17:9: error: expected expression before ‘{’ token
 stdt[1]={"Lady","Cook","s2345","Eng",'f',21};
         ^

lab7.c:18:9: error: expected expression before ‘{’ token
 stdt[2]={"James","Jackson","s33456","Eng",'m',17};
         ^

How can I do this correctly? 我该怎么做才能正确?

Here is the code so far: 这是迄今为止的代码:

#include <stdlib.h>
#include <stdio.h>

typedef struct {
    char *name;
    char *surname;
    char *UUN;
    char *department;
    char gender;
    int age;
} student_t;

int main() {
    int i;
    student_t stdt[6];
    stdt[0]={"John","Bishop","s1234","Inf",'m',18};
    stdt[1]={"Lady","Cook","s2345","Eng",'f',21};
    stdt[2]={"James","Jackson","s33456","Eng",'m',17};

    for(i=3;i<6;i++) {
        printf("First name: \n");
        scanf("%s",stdt[i].name);
        printf("Last name: \n");
        scanf("%s",stdt[i].surname);
        printf("UUN: \n");
        scanf("%s",stdt[i].UUN);
        printf("Department: \n");
        scanf("%s",stdt[i].department);
        printf("Gender (m/f): \n");
        scanf("%c",stdt[i].gender);
        printf("Age: \n");
        scanf("%d",stdt[i].age);
    }
    return 0;
}   

You're not "initializing" if you don't do it at the point of creation. 如果你在创作时没有这样做,你就不会“初始化”。 You can do: 你可以做:

student_t stdt[2] = { {"John", "Bishop", "s1234", "Inf", 'm', 18},
                      {"Lady", "Cook", "s2345", "Eng", 'f', 21}
                    };

for as many as you have. 尽可能多的。

It's OK to not explicitly provide values for each member of the array. 没有为数组的每个成员显式提供值是可以的。 For the ones you don't explicitly initialize, pointer members will be implicitly initialized to NULL , and numeric members will be implicitly initialized to 0 . 对于未显式初始化的指针成员,指针成员将被隐式初始化为NULL ,并且数值成员将被隐式初始化为0 In other words, this: 换句话说,这个:

student_t stdt[4] = { {"John", "Bishop", "s1234", "Inf", 'm', 18},
                      {"Lady", "Cook", "s2345", "Eng", 'f', 21}
                    };

is equivalent to this: 相当于:

student_t stdt[4] = { {"John", "Bishop", "s1234", "Inf", 'm', 18},
                      {"Lady", "Cook", "s2345", "Eng", 'f', 21},
                      {NULL, NULL, NULL, NULL, 0, 0},
                      {NULL, NULL, NULL, NULL, 0, 0}
                    };

For the curious, these rules derive from the C standard as follows. 对于好奇,这些规则来自C标准如下。

From C11 Section 6.7.9.21: 从C11第6.7.9.21节:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration. 如果括号括起的列表中的初始值设定项少于聚合的元素或成员,或者用于初始化已知大小的数组的字符串文字中的字符数少于数组中的元素,则聚合的其余部分应为隐式初始化与具有静态存储持续时间的对象相同。

and for "the same as objects that have static storage duration" we have Section 6.7.9.10: 对于“与具有静态存储持续时间的对象相同”,我们有6.7.9.10节:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. 如果未显式初始化具有自动存储持续时间的对象,则其值不确定。 If an object that has static or thread storage duration is not initialized explicitly, then: 如果未显式初始化具有静态或线程存储持续时间的对象,则:

  • if it has pointer type, it is initialized to a null pointer; 如果它有指针类型,则将其初始化为空指针;

  • if it has arithmetic type, it is initialized to (positive or unsigned) zero; 如果它有算术类型,则初始化为(正或无符号)零;

  • if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits; 如果它是一个聚合,则根据这些规则初始化(递归)每个成员,并将任何填充初始化为零比特;

  • if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits; 如果它是一个联合,则根据这些规则初始化(递归)第一个命名成员,并将任何填充初始化为零位;

A struct is an "aggregate" in the sense of the third bullet above. struct是上面第三个项目意义上的“聚合”。

You can do almost what you wrote if you use C99 'compound literals': 如果你使用C99'复合文字',你几乎可以做你写的:

stdt[0] = (student_t){ "John",  "Bishop",  "s1234",  "Inf", 'm', 18 };
stdt[1] = (student_t){ "Lady",  "Cook",    "s2345",  "Eng", 'f', 21 };
stdt[2] = (student_t){ "James", "Jackson", "s33456", "Eng", 'm', 17 };

However, this is assigning values to the array, not initializing the array. 但是,这是为数组赋值,而不是初始化数组。 Further, since the array is local to main() , the values in the other three elements of the array are indeterminate; 此外,由于数组是main()局部数组,因此数组的其他三个元素中的值是不确定的; you cannot assume anything about them. 你不能假设他们。

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

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