C语言--共用体(联合体)union

共用体:  多个变量(不同的数据类型)共用同一块内存空间, 但是同一时刻, 只能有一个变量起作用

共用体中起作用的的成员是最后一次存放的成员

 

 


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



//define union


union myUnion
{
char a;
short b;
int c;
};//这个三个变量共用一块内存空间



int main (void)
{


union myUnion temp;


temp.a = 0x1;
temp.b = 0x12;
temp.c = 0x1234;


printf("a:%c, b :%d,c:%d\n", temp.a,temp.b,temp.c); //共用体只使用最后一次赋值的变量
printf("sizeof %d", sizeof(temp));



}

a:4, b :4660,c:4660
sizeof 4

 

 

posted @ 2022-10-29 22:54  朵朵奇fa  阅读(134)  评论(0编辑  收藏  举报