温馨提示×

c语言结构体指针数组怎么初始化

小亿
311
2023-10-27 03:33:44
栏目: 编程语言

在C语言中,结构体指针数组的初始化可以通过以下几种方式进行:

  1. 逐个初始化:通过逐个为每个元素赋值。例如:
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;
  1. 使用静态初始化:通过静态方式初始化每个元素。例如:
struct Person {
    char name[20];
    int age;
};

struct Person *people[3] = {
    &(struct Person){"Tom", 20},
    &(struct Person){"Jerry", 25},
    &(struct Person){"Alice", 30}
};
  1. 使用循环初始化:通过循环为每个元素赋值。例如:
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];
}

需要注意的是,在使用完结构体指针数组后,需要手动释放内存。

0