共用体

用处对于因为某一条件不同,某一变量有多项向选择的情况下使用(对同一段内存有不同的分配作用。 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;
}
全部评论

相关推荐

Twilight_m...:经典我朋友XXXX起手,这是那种经典的不知道目前行情搁那儿胡编乱造瞎指导的中年人,不用理这种**
点赞 评论 收藏
分享
昨天 12:17
已编辑
商丘师范学院 Java
后来123321:别着急,我学院本大二,投了1100份,两个面试,其中一个还是我去线下招聘会投的简历,有时候这东西也得看运气
无实习如何秋招上岸
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 12:23
转人工😡
门口唉提是地铁杀:五次握手了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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