gpt4 book ai didi

c - Union中如何共享内存

转载 作者:行者123 更新时间:2023-11-30 18:54:40 24 4
gpt4 key购买 nike

下面的代码

#include <stdio.h>
#include <string.h>

union share
{
int num;
char str[3];
}share1;

int main()
{
strcpy(share1.str,"ab");
printf("str is %s and num is %d", share1.str, share1.num );
return 0;
}

我得到的输出为“str is ab and num is 25185”。str 按原样打印,但我如何获得 25185。

最佳答案

union 在内存中重叠。这意味着表示 int 的 2 个字节与字符串的前 2 个字符(字节)共享相同的内存位置。更改字符会自动更改 int,因为根据定义,它们是相同的东西...只是被区别对待,因为您可以将这两个字节作为 char 或 int 访问。

a -> 0x61
b -> 0x62

25185 -> 0x6261
^--- a
^----- b

关于c - Union中如何共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29853637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com