变量a所占字节数

union u{ char st[4]; int i; long 1;}struct A{int c; union u;}a;
2024-12-21 14:32:33
推荐回答(1个)
回答1:

union里面是几个数据通用一段内存地址。union占用的内存大小由union里面最大的地址决定。

这个问题可能是platform dependent,在我的32位linux机上,结果如下:

#include

union u
{
char string[4];
int i;
long l;
};

struct A
{
int anotherInt;
union u anotherUin;
};

int
main() {
int i;
long longInt;
char string[4];
union u u1;
struct A a;

printf("size of int is %d\n", sizeof(i));
printf("size of long is %d\n", sizeof(longInt));
printf("size of string is %d\n", sizeof(string));
printf("size of u is %d\n", sizeof(u1) );
printf("size of a is %d\n", sizeof(a) );

return 0;
}

运行结果如下:

size of int is 4
size of long is 4
size of string is 4
size of u is 4
size of a is 8

32位机上的int也是32位的,占4个bytes,默认long也是32位的,占4 bytes。4个char当然也是4个bytes.所以你的union占4 bytes.

而结构体struct A,就是一个4bytes int,加上一个4 bytes union,当然是8bytes了。