C语言中变长的结构体数组如何初始化
时间: 2023-06-23 16:46:53 浏览: 83
在 C 语言中,如果要定义变长的结构体数组,可以先定义一个指向结构体的指针,然后再动态地为该指针分配内存空间,从而实现变长数组的初始化。
下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[20];
int age;
};
int main() {
int n = 3;
struct student *s = (struct student*) malloc(n * sizeof(struct student));
if (s == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
for (int i = 0; i < n; i++) {
printf("Enter name and age for student %d: ", i+1);
scanf("%s %d", s[i].name, &s[i].age);
}
printf("The students' information:\n");
for (int i = 0; i < n; i++) {
printf("Name: %s, Age: %d\n", s[i].name, s[i].age);
}
free(s);
return 0;
}
```
在上面的示例代码中,首先定义了一个变量 `n`,表示要创建的结构体数组的长度。然后通过 `malloc()` 函数为指向结构体的指针 `s` 分配内存空间,大小为 `n * sizeof(struct student)`,即结构体的大小乘以数组的长度。接着通过循环为每个结构体成员的 `name` 和 `age` 成员赋值。最后释放已分配的内存空间。
需要注意的是,使用动态内存分配时,需要在程序结束前释放内存,避免内存泄漏。
相关推荐














