How to initialize and assign values to an array of structures in C programming language
There are two ways to initialize and assign values in a C language array of structures.
- Assign values one by one: You can use the method of assigning values one by one to assign values to each element of a structure array, for example:
struct Student {
char name[20];
int age;
};
int main() {
struct Student students[3];
strcpy(students[0].name, "Tom");
students[0].age = 18;
strcpy(students[1].name, "Alice");
students[1].age = 20;
strcpy(students[2].name, "Bob");
students[2].age = 19;
return 0;
}
- Initialization list can be used to initialize and assign values to a struct array, for example:
struct Student {
char name[20];
int age;
};
int main() {
struct Student students[3] = {
{"Tom", 18},
{"Alice", 20},
{"Bob", 19}
};
return 0;
}
Using the above two methods, it is possible to initialize and assign values to arrays of structures in the C language.