怎么借助指针开辟一个结构体数组
时间: 2023-11-23 13:45:37 浏览: 41
要借助指针开辟一个结构体数组,首先需要使用malloc函数动态分配内存空间。然后,可以使用指针来操作该结构体数组。
下面是一个示例代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Student {
int num;
char name[20];
char sex;
int age;
float score;
char addr[30];
};
int main() {
int size = 3; // 数组大小
struct Student* stu; // 定义指针变量
// 动态分配内存空间
stu = (struct Student*)malloc(size * sizeof(struct Student));
// 对结构体数组进行操作
for (int i = 0; i < size; i++) {
printf("请输入第%d个学生的信息:\n", i + 1);
printf("学号:");
scanf("%d", &(stu + i)->num);
printf("姓名:");
scanf("%s", &(stu + i)->name);
printf("性别:");
scanf(" %c", &(stu + i)->sex);
printf("年龄:");
scanf("%d", &(stu + i)->age);
printf("成绩:");
scanf("%f", &(stu + i)->score);
printf("地址:");
scanf("%s", &(stu + i)->addr);
}
// 打印结构体数组的信息
for (int i = 0; i < size; i++) {
printf("第%d个学生的信息:\n", i + 1);
printf("学号:%d\n", (stu + i)->num);
printf("姓名:%s\n", (stu + i)->name);
printf("性别:%c\n", (stu + i)->sex);
printf("年龄:%d\n", (stu + i)->age);
printf("成绩:%.2f\n", (stu + i)->score);
printf("地址:%s\n", (stu + i)->addr);
}
// 释放内存空间
free(stu);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)