c - union 嵌套在返回垃圾值的结构中

标签 c

一切正常,除了嵌套 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/

相关文章:

c - 使用 execvp 时输入重定向问题?

c - 为什么要包含当前.c文件的头文件?

c - 具有多个输入字段的用户界面

c - 测量计算时间

c - 访问 char 数组中结构的空指针

c - C中的Read()整数

C - 当程序读取文件时,不会注意到对文本文件所做的更改

c++ - 为什么 calloc 调用可能会导致内存损坏而 malloc 工作正常

c - 我想要更大的 pixbuf 渲染到 GtkSource Gutter

Java 找不到用于 native 方法的 .so C 库