(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$
 

 

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值