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

  代码如下:

 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 @ 2017-10-14 10:56  叕叒双又  阅读(1800)  评论(1编辑  收藏  举报