Variables of different types share the same memory space, and this memory space is a union.
Comparison between union and structure:
-
Structure elements have their own separate space
-
Union elements share space, and the size of the space is determined by the element that takes up the most space.
-
Struct elements do not affect each other, and copying a union will cause overwriting.
Define a union type named Test
, and then define a union variable named u1
:
#include <stdio.h>
union Test
{
int a;
double b;
char c[32];
};
int main(void)
{
union Test u1;
return 0;
}
At this time, the result of sizeof(union Test))
is 32, because the element that takes up the most space in the union is char c[32]
, which occupies 32 bytes.
Union elements share the same space:
#include <stdio.h>
union Test
{
int a;
double b;
char c[32];
};
int main(void)
{
union Test u1;
printf("a的地址是:%p\n",&u1.a);
printf("b的地址是:%p\n",&u1.b);
printf("c的地址是:%p\n",&u1.c);
return 0;
}
Output result:
a的地址是:000000000061FE00
b的地址是:000000000061FE00
c的地址是:000000000061FE00
You can see that variablesa
, b
, c
all share the same memory space