立即学习:https://edu.csdn/course/play/10534/378146?utm_source=blogtoedu

#include <stdio.h>
#include <string.h>

union Data1 {
	int a;
	char b;
	double c;
} t1;

union Data1 t2;

typedef union _Data2 {
	int a;
	char b;
	double c;
} Data2;

typedef union {
	int a;
	char b;
	double c;
} Data3;

// 匿名共用体
union {
	int a;
	char b;
	double c;
} x4;

union Score {
	float sc;
	char grade[16];  // A+ A B+ B
};

// 共用体和结构体
typedef struct {
	char name[32];
	// union Score score; 
	union {
		float sc;
		char grade[16];  // A+ A B+ B
	} score;
	unsigned age;
} Student;

int main() {
	union Data1 x1 = {0};
	Data2 x2 = {0};
	Data3 x3 = {0};
	Student stud = {0};

	printf("x1: a=%d, b=%c, c=%lf\n", x1.a, x1.b, x1.c);
	printf("x2: a=%d, b=%c, c=%lf\n", x2.a, x2.b, x2.c);
	printf("x3: a=%d, b=%c, c=%lf\n", x3.a, x3.b, x3.c);
	
	x1.a = 100;
	x1.b = 'A';
	x1.c = 1.2345;
	printf("set value >> x1: a=%d, b=%c, c=%lf\n", x1.a, x1.b, x1.c);

	strcpy(stud.name, "zhangsan");
	strcpy(stud.score.grade, "A+");
	stud.score.sc = 99.99;
	stud.age = 12;
	printf("stud >> name=%s, score.sc=%f, score.grade=%s, age=%u\n",
			stud.name, stud.score.sc, stud.score.grade, stud.age);
		
	return 0;
}

 

更多推荐

学习笔记(61):C语言入门到精通-共用体Union