C語言結構體數組的初始化方法有以下幾種:
逐個賦值:可以使用下標逐個為結構體數組的元素賦值,如:
struct Student {
char name[20];
int age;
};
struct Student students[3];
strcpy(students[0].name, "Tom");
students[0].age = 18;
strcpy(students[1].name, "Jerry");
students[1].age = 20;
strcpy(students[2].name, "Alice");
students[2].age = 19;
使用初始化列表:可以使用初始化列表為結構體數組的元素賦值,如:
struct Student {
char name[20];
int age;
};
struct Student students[3] = {
{"Tom", 18},
{"Jerry", 20},
{"Alice", 19}
};
先定義再賦值:可以先定義一個結構體數組,然后使用賦值語句為其元素賦值,如:
struct Student {
char name[20];
int age;
};
struct Student students[3];
struct Student temp;
strcpy(temp.name, "Tom");
temp.age = 18;
students[0] = temp;
strcpy(temp.name, "Jerry");
temp.age = 20;
students[1] = temp;
strcpy(temp.name, "Alice");
temp.age = 19;
students[2] = temp;
無論使用哪種方法,都可以完成結構體數組的初始化。