获取指向联合中变量的指针

发布于 2024-11-15 23:43:24 字数 195 浏览 3 评论 0原文

我只是想知道这是否是指向联合中字符的指针的正确语法:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

毁虫ゝ 2024-11-22 23:43:24

这是正确的语法。不过,您需要注意一个问题:x86 处理器是little-endian。这意味着,如果您部署在 x86 平台(这有点可能)或任何其他小端平台上,并且有一个整数,如下所示:

int value = 0x01020304;

,您的 char 数组将如下所示:

character[0] == 04;
character[1] == 03;
character[2] == 02;
character[3] == 01;

那么 字,字节将从内存中以相反的顺序读取。如果您需要使应用程序能够跨具有不同字节顺序的体系结构进行移植,这很快就会变得丑陋。

但是,如果您考虑到这一点或者不打算支持具有不同字节顺序的架构,那么应该没问题。

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.

老旧海报 2024-11-22 23:43:24
union myunion
{ char ch[4]; };
...
union myunion u;
void *ptr = (void*)&u;

此代码会将联合变量 u 的地址放入 ptr 中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文