c语言中结构体嵌套的解决方案-共用体

1.结构体嵌套:

问题:只是单纯的嵌套而已,解决结构体嵌套结构体的嵌套问题。

PS:上代码:

#include <stdio.h>
#include <stdlib.h>
typedef struct{
    char name[20];
    int age;
    char address[30];
}people;
typedef struct{
   people p1;
   char major[20];
}student;
int main()
{
    student s1;
    memcpy(s1.p1.address,"haerbin",sizeof("haerbin"));
    memcpy(s1.p1.name,"chen",sizeof("chen"));
    memcpy(s1.major, "iot",sizeof("iot"));
    s1.p1.age =23;
    printf("%s",s1.major);
    return 0;
}

2.共同体嵌套;

解决了多个结构体,其实主要是能让不同类型的数据放在一起调用。 

PS:代码:

#include <stdio.h>
#include <stdlib.h>

typedef union {
    struct{
        char name[20];
        int age;
        char address[30];
    };
    struct{
        char major[20];
    };
}student;
int main()
{
    student s1;
    memcpy(s1.address,"guangzhou",sizeof("guangzhou"));
    memcpy(s1.name,"li",sizeof("li"));
    memcpy(s1.major, "iot",sizeof("iot"));
    s1.age =23;
    printf("address:%s\n",s1.address);
    printf("name:%s\n",s1.name);
    printf("major:%sv",s1.major);
    printf("age:%d\n",s1.age);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42099097/article/details/107740069