含有指针变量的结构体的指针的应用

  代码如下:

复制代码
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4
 5 typedef struct _student{
 6     char *name;
 7     short id;
 8     double record;
 9     char sex;
10 } Student;
11
12 Student *initStudent(int i){
13     Student *ptrStu = (Student *)malloc(sizeof(Student));
14     ptrStu->name = (char *)malloc(sizeof(char) * 20);
15     printf("Input the %d'th student info: \n", i + 1);
16     printf("name: ");
17     scanf("%s", ptrStu->name);
18     printf("id: ");
19     scanf("%d", &ptrStu->id);
20     printf("record: ");
21     scanf("%lf", &ptrStu->record);
22     int tmp = getchar();
23     printf("sex: ");
24     scanf("%c", &ptrStu->sex);
25
26     return ptrStu;
27 }
28
29 void deleteStudent(Student *ptrStu){
30     free(ptrStu->name);
31     free(ptrStu);
32
33     return;
34 }
35
36 void displayStudent(Student *ptrStu){
37     printf("The student %s's info:\t", ptrStu->name);
38     printf("name: %s\t", ptrStu->name);
39     printf("id: %d\t", ptrStu->id);
40     printf("record: %lf\t", ptrStu->record);
41     printf("sex: %c\n", ptrStu->sex);
42
43     return;
44 }
45
46 int main(int argc, char **argv)
47 {
48     int size;
49     printf("please input the size: ");
50     scanf("%d", &size);
51     Student *arrStudent[size];
52     for(int i = 0; i < size; i++){
53         arrStudent[i] = initStudent(i);
54     }
55     for(int i = 0; i < size; i++){
56         displayStudent(arrStudent[i]);
57     }
58     for(int i = 0; i < size; i++){
59         deleteStudent(arrStudent[i]);
60     }
61     printf("test finished!\n");
62
63     return 0;
64 }
复制代码

  代码说明:

    (1)、第5-10行代码定义了结构体Student,成员变量name是char *型, record是double型;

    (2)、第12行代码函数initStudent()完成结构体Student *的初始化;

    (3)、第13行代码为结构体指针ptrStu申请内存空间;

    (4)、第14行代码为指针ptrStu的成员指针name申请内存空间

    (5)、第21行代码scanf("%lf", &ptrStu->record),务必注意double数据类型的数据输入的占位符是lf;

    (6)、第22行代码int tmp = getchar()将上边输入内容后的回车字符去掉;

    (7)、第29行代码函数deleteStudent()释放结构体指针,注意释放顺序;

    (8)、第36行代码函数displayStudent()输出指定结构体指针ptrStu的内容;

    (9)、第46行代码函数main()中完全遵照,申请内存,使用内存,释放内存的步骤使用内存;

posted @   叕叒双又  阅读(1808)  评论(1编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示