Getting a pointer to a variable in a union
I was just wondering if this is the correct syntax for a pointer to a char in a union:
union myunion {
char character[4];
}
... = 开发者_运维百科&(myunion.character[0])
It seems to produce the correct result in my application and I can't seem to find the correct syntax on the internet.
Thanks for your help.
It's the correct syntax. There's one gotcha you need to be aware of, however: x86 processors are little-endian. That means that if you deploy on an x86 platform (which is kinda likely) or any other little-endian platform, and have an integer such that:
int value = 0x01020304;
Then, your char
array will read as follow:
character[0] == 04;
character[1] == 03;
character[2] == 02;
character[3] == 01;
In other words, the bytes will read in reverse order from memory. If you need to make your application portable across architectures with a different endianness, this will quickly get ugly.
However, if you account for this or don't plan to support architectures with a different endianness, you should be fine.
union myunion
{ char ch[4]; };
...
union myunion u;
void *ptr = (void*)&u;
This code will place the address of the union variable u
into ptr
.
精彩评论