【问题标题】:Data in a union being overwritten联合中的数据被覆盖
【发布时间】:2017-10-30 19:09:02
【问题描述】:

我目前正在努力解决这个问题。我有一个联合,它有一个成员结构+变量,成员结构也包含一个成员结构+变量,这个成员结构包含变量。

我发现,当我试图为特定变量赋值时,我最终会覆盖一些以前赋值的数据。我有一种很好的感觉,这是由于指针没有增加。下面是一些示例代码:

struct Scale
{
    char Scale_Name[5];
    char notes[10];
};

struct Instrument
{
    char Inst_Name[5];
    struct Scale scales[5];
};

union Whole_Inst
{
    char InstrumentCount;
    struct Instrument Instruments[2]; 
};

union Whole_Inst Instrument1;

int main(void)
{
    char i, j, k;
    char TempArr[5] = {0x01, 0x02, 0x03, 0x04, 0x05};
    char NUMBER_OF_INST = 1;

    Instrument1.InstrumentCount = TempArr[0];

    printf("InstCount   = 0x%x\n", Instrument1.InstrumentCount);   

    for(j = 0; j < NUMBER_OF_INST; j++)
    {
        for(i = 0; i < 4; i++)
        {
            Instrument1.Instruments[0].Inst_Name[i] = TempArr[i+1];
            printf("\nInstName[%d] = 0x%x", i,  
            Instrument1.Instruments[0].Inst_Name[i]);   
        }
    }

    printf("\n\nInstCount   = 0x%x\n", i,  Instrument1.InstrumentCount);   

    system("PAUSE");    
    return 0;
}

我得到以下输出:

InstCount   = 0x1

InstName[0] = 0x2
InstName[1] = 0x3
InstName[2] = 0x4
InstName[3] = 0x5

InstCount   = 0x4
Press any key to continue . . .

有人可以指点我正确的方向吗?

亲切的问候 大卫

【问题讨论】:

  • 你为什么使用联合?不应该是结构体吗?
  • 当您设置Instrument1.InstrumentCount 时,您实际上是在覆盖仪器数据 - 联合成员映射到相同的内存空间,因此更改一个成员会更改所有联合成员。为此使用联合是没有意义的。
  • 你知道union 是干什么用的吗?这正是它正在做的事情。
  • 我投票结束这个问题作为题外话,因为 C 书迫切需要。问这种问题好丢人,打开维基看看就够了:在C and C++, untagged unions are expressed nearly exactly like structures (structs), except that **each data member begins at the same location in memory.**

标签: c pointers struct unions


【解决方案1】:

您的union 允许您存储一个 Inustruments 的计数或数组,但不能同时存储两者。这两条数据共享相同的内存。如果你改变一个,你就会覆盖另一个使用的内存。

如果要同时存储计数和数组,则需要使用struct 而不是union

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 2018-01-18
    • 2010-11-17
    相关资源
    最近更新 更多