Hi,all.
I am new to c++ and trying to figure out the amount of memory allocated to union to strut. Underneath is the code:
struct structure1
{
int i;
double d;
char ch;
};
union Packed
{
int i;
double d;
char ch;
}
int main(void)
{
structure1 objstruct;
Packed objP;
std::cout<<sizeof(objstruct);
std::cout<<sizeof(objP);
}
The output size of objstruct is not the arithmetic addition of its respective types, instead it is 24. Can someone help explain the reason?
For union, no matter how many items you have, the memory it occupies is always the size of the type which consume the maximum amount of memory. In this case, double.
How this is achieved?
Thank you in advance.