c语言结构体指针取值
时间: 2023-11-07 08:47:33 浏览: 113
好的,以下是用C语言的指向结构体指针,从键盘输入3名学生信息,包含学号、姓名、三门课程成绩的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_STUDENTS 3
struct student {
int id;
char name[20];
float score[3];
};
int main() {
struct student *ptr;
int i;
ptr = (struct student*) malloc(MAX_STUDENTS * sizeof(struct student));
for (i = 0; i < MAX_STUDENTS; i++) {
printf("请输入第%d个学生的信息:\n", i+1);
printf("学号:");
scanf("%d", &(ptr+i)->id);
printf("姓名:");
scanf("%s", (ptr+i)->name);
printf("三门课程成绩:");
scanf("%f %f %f", &(ptr+i)->score[0], &(ptr+i)->score[1], &(ptr+i)->score[2]);
}
printf("\n学生信息如下:\n");
for (i = 0; i < MAX_STUDENTS; i++) {
printf("学号:%d\n", (ptr+i)->id);
printf("姓名:%s\n", (ptr+i)->name);
printf("三门课程成绩:%.2f %.2f %.2f\n", (ptr+i)->score[0], (ptr+i)->score[1], (ptr+i)->score[2]);
}
free(ptr);
return 0;
}
```
这段代码中,我们定义了一个结构体 `student`,包含学号、姓名和三门课程成绩。然后我们使用指向结构体的指针 `ptr`,动态分配了一个大小为 `MAX_STUDENTS` 的结构体数组。
接着,我们使用 `for` 循环,从键盘输入每个学生的信息,包括学号、姓名和三门课程成绩。注意,我们使用了指向结构体的指针 `ptr` 来访问每个学生的信息。
最后,我们使用 `for` 循环,输出每个学生的信息,包括学号、姓名和三门课程成绩。
最后,我们使用 `free` 函数释放了动态分配的内存。
希望这个示例能够帮助你理解如何使用指向结构体的指针从键盘输入学生信息。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)