【问题标题】:C variables in struct have same address each otherstruct中的C变量彼此具有相同的地址
【发布时间】: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。在联合中,countitem(或两者都不是)在任何时间点都有效,因此它们的表示可以安全地覆盖在内存中。

标签: c pointers struct typedef


【解决方案1】:

因为plist_t 不是结构,而是联合

在 C 中,联合的每个成员都从相同的内存地址开始。

如果您想单独更改它们,只需将plist_t 转换为结构即可:

typedef struct ptid_lst {
    count_t count; 
    ptid_t  item[1];
} plist_t;

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 2015-10-25
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多