我正在做一个简单的学生数据库程序练习,我不确定如何初始化结构数组。我试图用编译时已知的值初始化数组 stdt[]
的前 3 个元素,然后接下来的 3 个学生的信息将从用户输入中填充。编译时出现错误:
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};
^
我怎样才能正确地做到这一点?
这是目前的代码:
#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;
}
最佳答案
如果您不在创建时进行初始化,您就不算在“初始化”。你可以这样做:
student_t stdt[2] = { {"John", "Bishop", "s1234", "Inf", 'm', 18},
{"Lady", "Cook", "s2345", "Eng", 'f', 21}
};
有多少就有多少。
可以不显式地为数组的每个成员提供值。对于未显式初始化的,指针成员将被隐式初始化为NULL
,数字成员将被隐式初始化为0
。换句话说,这:
student_t stdt[4] = { {"John", "Bishop", "s1234", "Inf", 'm', 18},
{"Lady", "Cook", "s2345", "Eng", 'f', 21}
};
等同于:
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}
};
出于好奇,这些规则源自 C 标准,如下所示。
来自 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.
对于“与具有静态存储持续时间的对象相同”,我们有第 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;
struct
是上述第三点意义上的“聚合”。
关于c - 在 C 中初始化结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26685392/