union共用体的使用

    技术2024-08-19  59

    #include<stdio.h> #include<stdlib.h> union test { int a; char b; short d; }; int main() { //union test类型名 //tmp是变量名 union test tmp; //1.共用体,所有成员共用一段内存空间 //2.所有成员的首地址是一样的 printf("%p ,%p ,%p\n",&tmp.a,&tmp.b,&tmp.d); //3.共用体的大小为最大成员的大小 printf("sizeof(union test) = %lu\n",sizeof(union test)); //4.改变一个成员。会影响到另外的成员 //左边是高位,右边是低位 //高位放高地址。低位放地址(小端) tmp.d=0xaabbccdd; printf("c1 = %x\n",tmp.d);//aabbccdd printf("a = %x\n",tmp.a);//dd printf("b =%x\n",tmp.b); //ccdd tmp.a=0x11; printf("c1 = %x\n",tmp.d);//aabbcc11 printf("a = %x\n",tmp.a);//11 printf("b =%x\n",tmp.b); //cc11 }

    Processed: 0.054, SQL: 9