鱼C论坛

 找回密码
 立即注册
查看: 2157|回复: 2

[已解决]共用体

[复制链接]
发表于 2021-6-10 21:14:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
为什么输出时的数据于输入时的数据不服?
printf(" test.i: %d\n",test.i);
        printf(" test.pi:%.2f\n",test.pi);
        printf("test.str:%s\n",test.str);
#include<stdio.h>
#include<string.h>
union Test  
{
        int i;
        double pi;
        char str[6];
 };
 int main(void)
 {
         union Test test;
         test.i=520;
         test.pi=3.14;
         strcpy(test.str,"FishC");
         
         printf("addr of test.i: %p\n",&test.i);
         printf("addr of test.pi:%p\n",&test.pi);
         printf("addr of test.str:%p\n",&test.str);
         printf(" test.i: %d\n",test.i);
         printf(" test.pi:%.2f\n",test.pi);
         printf("test.str:%s\n",test.str);
         return 0;
 }
最佳答案
2021-6-10 21:40:38
$ ./main
addr of test.i: 0xffffcc38
addr of test.pi:0xffffcc38
addr of test.str:0xffffcc38
 test.i: 1752394054
 test.pi:3.13
test.str:FishC
对 test 的最后一次赋值是 strcpy(test.str,"FishC");
所以 test.str:FishC 这个输出没问题,(共用体)union 就是共用一个位置,后一个覆盖前一个,只会保留最后一次赋值
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-6-10 21:40:38 | 显示全部楼层    本楼为最佳答案   
$ ./main
addr of test.i: 0xffffcc38
addr of test.pi:0xffffcc38
addr of test.str:0xffffcc38
 test.i: 1752394054
 test.pi:3.13
test.str:FishC
对 test 的最后一次赋值是 strcpy(test.str,"FishC");
所以 test.str:FishC 这个输出没问题,(共用体)union 就是共用一个位置,后一个覆盖前一个,只会保留最后一次赋值
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-6-10 23:13:18 | 显示全部楼层
公用一个内存啊(取最大的成员长度)  
会互相覆盖      
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 14:28

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表