含有指針變量的結構體的指針的應用


  代碼如下:

 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()中完全遵照,申請內存,使用內存,釋放內存的步驟使用內存;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM