在C语言中,结构体指针数组的初始化可以通过以下几种方式进行: 逐个初始化:通过逐个为每个元素赋值。例如: struct Pers
在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];
}
需要注意的是,在使用完结构体指针数组后,需要手动释放内存。
--结束END--
本文标题: c语言结构体指针数组怎么初始化
本文链接: https://www.lsjlt.com/news/482429.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0