gpt4 book ai didi

C: union 成员在编译时被破坏

转载 作者:太空狗 更新时间:2023-10-29 15:57:37 25 4
gpt4 key购买 nike

这是一个C代码,可以将成员信息打印到控制台。

#include "learnc0006.h"
#include "stdio.h"
#include "string.h"

union Member {
char name[20];
int age;
int height;
};

void printMember(union Member data);

int learnc0006() {
union Member data;

strcpy(data.name, "Rico Angeloni");
data.age = 30;
data.height = 175;

printMember(data);
return 0;
}

void printMember(union Member data) {
printf("Name: %s\n", data.name);
printf("Age: %d\n", data.age);
printf("Height: %d\n", data.height);
}

我原以为不会有问题,但它显示的结果有点不同,打印出一个看起来很奇怪的名称值,而不是显示正确的值。

Name: \257
Age: 175
Height: 175

任何好的解决方案将不胜感激。谢谢!

最佳答案

我认为您可能将结构与 union 混淆了。在 union 中,元素共享内存。

这意味着当您写入 union 体的 age 字段时,您同时覆盖了 heightname 的内容,这不是您想要的。当您写入最后写入的 height 时也是如此。您可以很好地观察到这一点,因为最后 ageheight 的值相同,而 name 的第一个字符实际上是字符数字 175(显示为转义八进制 \257)。

尝试使用 struct 而不是 union

关于C: union 成员在编译时被破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31625062/

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