结构体数组与用malloc申请结构体空间的对比
生活随笔
收集整理的這篇文章主要介紹了
结构体数组与用malloc申请结构体空间的对比
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
結(jié)構(gòu)體數(shù)組與用malloc申請結(jié)構(gòu)體空間的對比
文章標(biāo)題聽起來很拗口,可能我描述的不太清楚,還是看例程吧:
我先寫以前最早會用的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
",p_student->name);
20 printf("age:%d
",p_student->age);
21
22 free(p_student);
23 p_student=NULL;//注意,釋放掉了malloc空間,但結(jié)構(gòu)體指針依然存在,仍需要指向NULL;
24 return 0;
25 }
上面程序簡單明了,就是申請個結(jié)構(gòu)體指針,然后開辟一段內(nèi)存空間,準(zhǔn)備存放“struct student”類型的變量數(shù)據(jù),變量都初始化后,打印出來,最后釋放malloc空間。
下面再來一個結(jié)構(gòu)體數(shù)組:
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
",p_student->name);
16 printf("age:%d
",p_student->age);
17 return 0;
18 }
這是結(jié)構(gòu)體數(shù)組,就是:“struct student”類型的數(shù)組“p_student”,空間大小為“sizeof(struct student)”,初始化時,直接在后面寫上就行了。
通過上面兩個例子,我發(fā)現(xiàn)第二種結(jié)構(gòu)體數(shù)組好用些。
總結(jié)
以上是生活随笔為你收集整理的结构体数组与用malloc申请结构体空间的对比的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 生存日记目标偏移任务怎么做
- 下一篇: 条令考试小程序辅助器_应知应会条令纲要学