在C語言中,結構體指針數組的初始化可以通過以下幾種方式進行:
struct Person {
char name[20];
int age;
};
struct Person *people[3];
people[0] = malloc(sizeof(struct Person));
strcpy(people[0]->name, "Tom");
people[0]->age = 20;
people[1] = malloc(sizeof(struct Person));
strcpy(people[1]->name, "Jerry");
people[1]->age = 25;
people[2] = malloc(sizeof(struct Person));
strcpy(people[2]->name, "Alice");
people[2]->age = 30;
struct Person {
char name[20];
int age;
};
struct Person *people[3] = {
&(struct Person){"Tom", 20},
&(struct Person){"Jerry", 25},
&(struct Person){"Alice", 30}
};
struct Person {
char name[20];
int age;
};
struct Person *people[3];
char names[3][20] = {"Tom", "Jerry", "Alice"};
int ages[3] = {20, 25, 30};
for (int i = 0; i < 3; i++) {
people[i] = malloc(sizeof(struct Person));
strcpy(people[i]->name, names[i]);
people[i]->age = ages[i];
}
需要注意的是,在使用完結構體指針數組后,需要手動釋放內存。