共用体

用处对于因为某一条件不同,某一变量有多项向选择的情况下使用(对同一段内存有不同的分配作用。 alt

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

int main() {
    struct person {
        int num;
        char name[10];
        char gender;
        char job;
        union {
            int class1;
            char position[10];
        } en;
    } person[2];
    for (int i = 0; i < 2; i++) {
        scanf("%d %s %c %c", &person[i].num, person[i].name, &person[i].gender, &person[i].job);
        if (person[i].job == 's') {
            scanf("%d", &person[i].en.class1);
            printf("\n");
            printf("%d %s %c %c %d",person[i].num,person[i].name,person[i].gender,person[i].job,person[i].en.class1);
        }
        else {
            scanf("%s", person[i].en.position);
            printf("\n");
            printf("%d %s %c %c %s", person[i].num, person[i].name, person[i].gender, person[i].job,
                   person[i].en.position);
        }

    }
    return 0;
}

注意:共用体一次只能给其中的一个成员赋值,当给另外一个成员赋值的时候,上一次赋值的结果自动销毁,

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

using namespace std;

int main() {
    struct person {
        int num;
        char name[10];
        char gender;
        char job;
        union {
            int class1;
            char position[10];
        } en;
    } person[2];
    scanf("%d", &person[0].en.class1);
    scanf("%s", person[0].en.position);
    cout <<person[0].en.position;
    return 0;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 11:55
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 18:05
哈哈哈哈哈感觉朋友找工作的已经疯掉了,直接上图
码农索隆:真老板娘:“我嘞个去,这不我当年的套路吗
点赞 评论 收藏
分享
07-07 17:06
已编辑
深圳技术大学 golang
点赞 评论 收藏
分享
07-02 22:46
门头沟学院 Java
码农索隆:hr:“管你投没投,先挂了再说”
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务