获取指向联合中变量的指针
我只是想知道这是否是指向联合中字符的指针的正确语法:
union myunion {
char character[4];
}
... = &(myunion.character[0])
它似乎在我的应用程序中产生了正确的结果,但我似乎无法在互联网上找到正确的语法。
感谢您的帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是正确的语法。不过,您需要注意一个问题:x86 处理器是little-endian。这意味着,如果您部署在 x86 平台(这有点可能)或任何其他小端平台上,并且有一个整数,如下所示:
,您的 char 数组将如下所示:
那么 字,字节将从内存中以相反的顺序读取。如果您需要使应用程序能够跨具有不同字节顺序的体系结构进行移植,这很快就会变得丑陋。
但是,如果您考虑到这一点或者不打算支持具有不同字节顺序的架构,那么应该没问题。
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:
Then, your
char
array will read as follow: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.
此代码会将联合变量
u
的地址放入ptr
中。This code will place the address of the union variable
u
intoptr
.