union

union的变量共用内存.

#include 



typedef struct Leix {
    char* profession;
    union {    
        int score;
        char* course;
    };
}Leix;

int main() {
    Leix student1 = { "Student",90 }; 
    Leix teacher1 ;

    teacher1.profession = "Teacher"; teacher1.score = 91; teacher1.course = "Chinese";
    printf("teacher: profession=%s,score=%d,course=%s", teacher1.profession, teacher1.score,teacher1.course);

    return 0;
}

因为共用体共用内存,上述代码的teacher变量不能同时初始化score和sourse,会导致数据覆盖;

共用体union里面的变量只能使用一个.

你可能感兴趣的:(算法)