zoukankan      html  css  js  c++  java
  • 结构体数组与用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)”,初始化时,直接在后面写上就行了。

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

     

     

  • 相关阅读:
    UVA 254 Towers of Hanoi
    UVA 701 The Archeologists' Dilemma
    UVA 185 Roman Numerals
    UVA 10994 Simple Addition
    UVA 10570 Meeting with Aliens
    UVA 306 Cipher
    UVA 10160 Servicing Stations
    UVA 317 Hexagon
    UVA 10123 No Tipping
    UVA 696 How Many Knights
  • 原文地址:https://www.cnblogs.com/data-base-of-ssy/p/6955745.html
Copyright © 2011-2022 走看看