【发布时间】:2020-04-10 07:33:21
【问题描述】:
定义代码:
#include <stdio.h>
#include <string.h>
typedef int count_t;
typedef struct ptid_t {
short index;
short ioffset;
unsigned char type;
unsigned char networkType;
} ptid_t;
typedef union ptid_lst {
count_t count;
ptid_t item[1];
} plist_t;
主要代码:
int main(void) {
plist_t test;
memset(&test, 0x0, sizeof(plist_t));
test.count = 0xABCDABCD;
printf("%x\n", test.count);
printf("%x\n", test.item[0].index);
printf("%x\n", test.item[0].ioffset);
return 0;
}
控制台输出:
abcdabcd
ffffabcd
ffffabcd
我只是想改变结构第一个值'count',但其他变量都改变了。
更改值是 plist_t 中的“计数”。但是,为什么 index 和 ioffset 变量都被改变了?
由于这种情况,我尝试获取变量的地址和结果:
0x80479f4
0x80479f4
0x80479f6
'count' 变量和 item[0] 结构具有相同的地址。为什么会出现这种情况?
在相反的情况下也是一样的。
int main(void) {
plist_t test;
memset(&test, 0x0, sizeof(plist_t));
test.item[0].index = 0xabcd;
test.item[0].ioffset = 0xabc0;
printf("%x\n", test.count);
printf("%x\n", test.item[0].index);
printf("%x\n", test.item[0].ioffset);
return 0;
}
console output:
abc0abcd
ffffabcd
ffffabc0
【问题讨论】:
-
你明白
union在 C 中是什么吗?您的问题应该是“联合中的 C 变量具有相同的地址”。因为您实际上是在比较联合中的字段而不是结构中的字段。 -
我想你想要一个
struct而不是union。在联合中,count或item(或两者都不是)在任何时间点都有效,因此它们的表示可以安全地覆盖在内存中。