结构体中套结构体如何申请动态内存
时间: 2023-12-18 17:28:36 浏览: 91
结构体中套结构体申请动态内存的方法如下:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义内部结构体
typedef struct {
int year;
int month;
int day;
} Date;
// 定义外部结构体
typedef struct {
char name[20];
int age;
Date *birthday; // 指向内部结构体的指针
} Person;
int main() {
// 动态分配内部结构体
Date *birthday = (Date *)malloc(sizeof(Date));
birthday->year = 2000;
birthday->month = 1;
birthday->day = 1;
// 动态分配外部结构体
Person *person = (Person *)malloc(sizeof(Person));
strcpy(person->name, "Tom");
person->age = 20;
person->birthday = birthday;
// 输出结果
printf("Name: %s\n", person->name);
printf("Age: %d\n", person->age);
printf("Birthday: %d-%d-%d\n", person->birthday->year, person->birthday->month, person->birthday->day);
// 释放内存
free(birthday);
free(person);
return 0;
}
```
阅读全文