8.4结构体嵌套

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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值