1.结构体嵌套结构体变量
struct A {
int a;
int b;
};
struct B {
struct A sa;
int c;
int d;
};
代码如下:
//结构体嵌套结构体变量
#include <stdio.h>
typedef struct birthday {
int year;
int month;
int day;
}birth_t;
typedef struct student {
char name[32];
int age;
birth_t birth; //嵌套结构体变量来存储学生的出生日期
}stu_t;
int main(void) {
stu_t stu1 = {"小白", 27, {1995, 11, 13}};
stu_t *pstu = &stu1; //pstu指向stu1
printf("%s, %d, %d-%d-%d\n",
stu1.name, stu1.age,
stu1.birth.year, stu1.birth.month, stu1.birth.day);
printf("%s, %d, %d-%d-%d\n",
pstu->name, pstu->age,
pstu->birth.year, pstu->birth.month, pstu->birth.day);
stu1.age++;
pstu->birth.year = 2003;
printf("%s, %d, %d-%d-%d\n",
stu1.name, stu1.age,
stu1.birth.year, stu1.birth.month, stu1.birth.day);
printf("%s, %d, %d-%d-%d\n",
pstu->name, pstu->age,
pstu->birth.year, pstu->birth.month, pstu->birth.day);
return 0;
}
2.嵌套结构体指针
struct A {
int a;
int b;
};
struct B {
struct A *psa;
int c;
int d;
};
在这里!!!!要注意,在初始化时,指针的初始化需要一开始给NULL!!!而后通过分配结构体变量,将其地址赋给定义的指针进行初始化!!!!
代码如下:
//结构体嵌套结构体指针变量
#include <stdio.h>
typedef struct birthday {
int year;
int month;
int day;
}birth_t;
typedef struct student {
char name[32];
int age;
birth_t *pbirth; //嵌套结构体指针变量来指向存储学生出生日期的内存空间
}stu_t;
int main(void) {
stu_t stu1 = {.name = "游哥", .age = 18, .pbirth = NULL};
stu_t *pstu = &stu1; //pstu指向stu1
//分配内存来存储学生出生日期
birth_t birth = {2004, 2, 2};
//让pbirth指向birth有效内存
stu1.pbirth = &birth; //或者pstu->pbirth = &birth;
printf("%s, %d, %d-%d-%d\n",
stu1.name, stu1.age,
stu1.pbirth->year, stu1.pbirth->month, stu1.pbirth->day);
printf("%s, %d, %d-%d-%d\n",
pstu->name, pstu->age,
pstu->pbirth->year, pstu->pbirth->month, pstu->pbirth->day);
stu1.age++;
pstu->pbirth->year = 2003;
printf("%s, %d, %d-%d-%d\n",
stu1.name, stu1.age,
stu1.pbirth->year, stu1.pbirth->month, stu1.pbirth->day);
printf("%s, %d, %d-%d-%d\n",
pstu->name, pstu->age,
pstu->pbirth->year, pstu->pbirth->month, pstu->pbirth->day);
return 0;
}