How are the union members stored?

后端 未结 2 994
栀梦
栀梦 2020-12-31 06:14
union test
{
 int i;
 char ch;
}t;
int main()
{
 t.ch=20;
}

Suppose sizeof(int)==2 and let the memory addresses allocated for t are 20

2条回答
  •  囚心锁ツ
    2020-12-31 06:49

    test would take two bytes, and so would be allocated at address 2000, 2002, etc. And any value for each instance of the union would be stored starting at that base address.

    Each member of the union would be stored at the same address for that instance of the union. That's why you can only store one type of value in a union at the same time. Therefore, unions occupy the number of bytes required for the largest member.

提交回复
热议问题