阅读量:3
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;
无论使用哪种方法,都可以完成结构体数组的初始化。