struct中的C变量彼此具有相同的地址

问题描述 投票:-2回答:1

定义代码:

#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中为“ count”。但是,为什么索引和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
c pointers struct typedef
1个回答
1
投票

因为plist_t不是结构,所以是一个并集

© www.soinside.com 2019 - 2024. All rights reserved.