(union, struct) 相互嵌套使用----技巧(你肯定没见过)


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

// 参考 Glibc库源码 sig_info.h
typedef struct info{
	int age;
	union {
		int code;
		struct {
			int pid;
			int uid;
		} id;
		struct {
			int KM;
			char *addr_name;
		} address;
	} u;
} info_t;

#define code 		u.code
#define pid 		u.id.pid
#define uid			u.id.uid
#define KM  		u.address.KM
#define addr_name   u.address.addr_name

int main(int argc, char **argv)
{
	info_t info;
	
	info.age 	= 20;
	info.code   = 5;
	
	printf("age = %d\n", info.age);			// 20
	printf("code = %d\n", info.code);		// 5
	
	printf("----------------------\n");
	info.pid = 123;
	printf("age = %d\n", info.age);			// 20
	printf("code = %d\n", info.code);		// 123, 因为code变量与id变量共用一块内存
	printf("pid = %d\n", info.pid);			// 123

	printf("----------------------\n");
	info.KM = 789;
	printf("age = %d\n",  info.age);		// 20
	printf("code = %d\n", info.code);		// 789, 因为code变量与address变量共用一块内存
	printf("pid = %d\n",  info.pid);		// 789, 因为id变量与address变量共用一块内存
	printf("KM = %d\n",   info.KM);			// 789
	return 0;
}

执行结果:

book@gui_hua_shu:~/test$ gcc union_struct.c
book@gui_hua_shu:~/test$ ./a.out
age = 20
code = 5
----------------------
age = 20
code = 123
pid = 123
----------------------
age = 20
code = 789
pid = 789
KM = 789
book@gui_hua_shu:~/test$
 

猜你喜欢

转载自blog.csdn.net/qq_38813056/article/details/85244969
今日推荐