I'm confused about unions and how they allocate memory. Say I have:
union Values
{
int i开发者_JAVA技巧value;
double dvalue;
};
Values v;
So I know the int uses 4 bytes and the double uses 8 bytes, so there are 8 bytes allocated in total (I think), with that said how much memory would v
use?
You've pretty much answered your own question: given a four-byte int
and an 8-byte double
, v
would use 8 bytes of memory.
If unsure, you could compile and run a simple program that'll print out sizeof(v)
.
Given that int
is 4 bytes and double
is 8 bytes (which is not guaranteed by the language), sizeof (Values)
is at least 8 bytes.
Most commonly it will be exactly 8 bytes (more generally, sizeof (int)
or sizeof (double)
, whichever is larger), but compilers are permitted to add unnamed padding to structs and unions. For structs, any such padding can be between any two mebers, or after the last one; for unions, it can only be at the end.
The purpose of such padding is to allow for better alignment. For example, given:
union u {
char c[5];
int i;
};
if int
is 4 bytes and requires 4-byte alignment, the compiler will have to add padding to make sizeof (union u)
at least 8 bytes.
In your particular case, there's probably no reason to add any padding, but you shouldn't assume that there isn't any. If you need to know the size of the union, just use sizeof
.
精彩评论