结构体数组与用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
",p_student->name);
20     printf("age:%d
",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
",p_student->name);
16     printf("age:%d
",p_student->age);
17     return 0;
18 }

  这是结构体数组,就是:“struct student”类型的数组“p_student”,空间大小为“sizeof(struct student)”,初始化时,直接在后面写上就行了。

  通过上面两个例子,我发现第二种结构体数组好用些。

 

 

原文地址:https://www.cnblogs.com/data-base-of-ssy/p/6955745.html