C language - union body (Union)

Union

Preface: Look at an actual requirement:

image-20221101190542338

Traditional way to solve:

//定义结构体,根据人员的职业,使用对应的成员变量
struct Person{
    
    
char name[20];
int num;
char sex;
char profession;
float score;	//学生使用score
char course[20];//老师使用course
};

**Problem analysis in the traditional way:** It will cause a waste of space, for example, students only use score, but it also occupies 20 bytes of course members

solution:

(1) Make struct Stu and struct Teacher [but if there are many occupations, it will correspond to multiple structure types, which is not conducive to management]

(2) Here the union is thus proposed

1. Basic introduction of the community

(1) The union belongs to the structural type , which can contain multiple members of different types. Similar to structs, but different

(2) The union is sometimes called a union or a union, and the definition format is

union 共用体名{
    
    
	成员列表
}

(3) The difference between a structure and a union is that each member of the structure occupies different memory and has no influence on each other, while all members of the union occupy a section of memory , and modifying one member will affect all other members

2. Quick Start

(1) Three ways to define union types and union variables (same as structure)

image-20221101192423029

image-20221101204215288

Why are the above running results different from what we imagined?

3. Explain the memory layout of the code:

image-20221101204355162

4. Community memory layout analysis

image-20221101204521715

5. Final practice

image-20221101225832133

analyze:

f and m represent female and male respectively, s represents student, and t represents teacher. It can be seen that the data contained in students and teachers is different (score/course). Now it is required to put this information in the same form, and design a program to input personnel information and then output it.

If everyone's information is regarded as a structure variable, then the first four member variables of teachers and students are the same, and the fifth member variable may be score or course. When the value of the fourth member variable is s, the fifth member variable is score; when the value of the fourth member variable is t, the fifth member variable is course.

code:

#include <stdio.h>
#include <stdlib.h>
#define TOTAL 2  //人员总数
struct{
    
    
    char name[20];
    int num;
    char sex;
    char profession;
    union{
    
    
        float score;
        char course[20];
    } sc;
} bodys[TOTAL];
int main(){
    
    
    int i;
    //输入人员信息
    for(i=0; i<TOTAL; i++){
    
    
        printf("Input info: ");
        scanf("%s %d %c %c", bodys[i].name, &(bodys[i].num), &(bodys[i].sex), &(bodys[i].profession));
        if(bodys[i].profession == 's'){
    
      //如果是学生
            scanf("%f", &bodys[i].sc.score);
        }else{
    
      //如果是老师
            scanf("%s", bodys[i].sc.course);
        }
        fflush(stdin);
    }
    //输出人员信息
    printf("\nName\t\tNum\tSex\tProfession\tScore / Course\n");
    for(i=0; i<TOTAL; i++){
    
    
        if(bodys[i].profession == 's'){
    
      //如果是学生
            printf("%s\t%d\t%c\t%c\t\t%f\n", bodys[i].name, bodys[i].num, bodys[i].sex, bodys[i].profession, bodys[i].sc.score);
        }else{
    
      //如果是老师
            printf("%s\t%d\t%c\t%c\t\t%s\n", bodys[i].name, bodys[i].num, bodys[i].sex, bodys[i].profession, bodys[i].sc.course);
        }
    }
    return 0;
}

operation result:

image-20221101231147853

Guess you like

Origin blog.csdn.net/m0_53415522/article/details/127643464