Union嵌套在返回垃圾值的结构中

时间:2014-06-24 21:22:26

标签: c

一切正常,但嵌套联合没有得到更新。我正在使用mingw编译器。 我正在学习关于C的编码,并在出现这个问题时尝试嵌套联合和其他东西。请告诉我什么是代码的错误,以及可能的调试。我发现它没有任何问题。

输出:

一个:3

B:3

l.a:8

l.b:5

union:-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;
}

1 个答案:

答案 0 :(得分:2)

tr.n.d的类型为float%d格式说明符告诉printf将其视为int。请尝试将格式说明符更改为%f

printf("a: %d\nb: %d\nl.a: %d\nl.b: %d\nunion: %f"
//                                              ^

或者,您可以初始化工会的int成员:

one tr={2,3,{4,5},{.c=42}};