一切正常,除了嵌套 union 没有得到更新。我正在使用 mingw 编译器。 当这个问题出现时,我只是在学习有关 C 的编码并尝试嵌套 union 和其他东西。请告诉我代码的错误是什么,以及可能的调试。我找不到任何问题。
输出:
一个:3
b:3
洛杉矶:8
体重:5
联盟:-536870912
#include<stdio.h>
#include<conio.h>
typedef struct
{
int a;
int b;
} two;
typedef union
{
int c;
float d;
} ad;
typedef struct
{
int a;
int b;
two l;
ad n; /*This is nested union that is not getting updated*/
} one;
void trr(one *p);
int main()
{
one tr={2,3,{4,5},{.d=5.43}};
trr(&tr);
printf("a: %d\nb: %d\nl.a: %d\nl.b: %d\nunion: %d",tr.a,tr.b,tr.l.a,tr.l.b,tr.n.d);
return 0;
}
void trr(one *p)
{
p->a=(*p).a+1;
p->l.a=p->l.a*2;
}
最佳答案
tr.n.d
的类型为 float
。然而,%d
格式说明符告诉 printf
将其视为 int
。尝试将格式说明符改为 %f
printf("a: %d\nb: %d\nl.a: %d\nl.b: %d\nunion: %f"
// ^
或者,您可以初始化 union 体的 int
成员:
one tr={2,3,{4,5},{.c=42}};
关于c - union 嵌套在返回垃圾值的结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24396549/