动态分配结构体内存

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/minwenping/article/details/78822963
struct Teacher{
    char name[20];
};

//嵌套结构体
struct Student{
    int age;
    struct Teacher teacher;//内存大小,指针也是int类型
};
  //动态分配结构体内存
   struct Student *p1 = (Student* )malloc(sizeof(struct Student)* 2);
   struct Student *temp = p1;
   temp->age = 18;
   strcpy(temp->teacher.name, "雪碧");
   temp++;
   temp->age = 36;
   strcpy(temp->teacher.name, "芬达");
   struct Student *a = p1;
   printf("%#X=%#X\n",a,temp);
   //循环遍历输出
   for (; a <p1 + 2; a++)
   {
       printf("测试结构体指针遍历输出 %d,%s\n", a->age, a->teacher.name);
   }
   //手动释放内存
   free(p1);

这里写图片描述

猜你喜欢

转载自blog.csdn.net/minwenping/article/details/78822963
今日推荐