結構體數組與用malloc申請結構體空間的對比


結構體數組與用malloc申請結構體空間的對比

  文章標題聽起來很拗口,可能我描述的不太清楚,還是看例程吧:

  我先寫以前最早會用的malloc:

  

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 struct student
 6 {
 7     char *name;
 8     int age;
 9 };
10 
11 int main()
12 {
13     struct student *p_student=NULL;
14     p_student=((struct student *)malloc(sizeof(struct student)));
15 
16     p_student->name="Tom";
17     p_student->age=23;
18 
19     printf("name:%s\n",p_student->name);
20     printf("age:%d\n",p_student->age);
21 
22     free(p_student);
23   p_student=NULL;//注意,釋放掉了malloc空間,但結構體指針依然存在,仍需要指向NULL;
24 return 0; 25 }

  上面程序簡單明了,就是申請個結構體指針,然后開辟一段內存空間,准備存放“struct student”類型的變量數據,變量都初始化后,打印出來,最后釋放malloc空間。

  下面再來一個結構體數組:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 struct student
 6 {
 7     char *name;
 8     int age;
 9 };
10 
11 int main()
12 {
13     struct student p_student[sizeof(struct student)]={"Tom",23};
14 
15     printf("name:%s\n",p_student->name);
16     printf("age:%d\n",p_student->age);
17     return 0;
18 }

  這是結構體數組,就是:“struct student”類型的數組“p_student”,空間大小為“sizeof(struct student)”,初始化時,直接在后面寫上就行了。

  通過上面兩個例子,我發現第二種結構體數組好用些。

 

 


免責聲明!

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



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