鱼C论坛

 找回密码
 立即注册
查看: 2379|回复: 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);
  1. #include<stdio.h>
  2. #include<string.h>
  3. union Test  
  4. {
  5.         int i;
  6.         double pi;
  7.         char str[6];
  8. };
  9. int main(void)
  10. {
  11.         union Test test;
  12.         test.i=520;
  13.         test.pi=3.14;
  14.         strcpy(test.str,"FishC");
  15.        
  16.         printf("addr of test.i: %p\n",&test.i);
  17.         printf("addr of test.pi:%p\n",&test.pi);
  18.         printf("addr of test.str:%p\n",&test.str);
  19.         printf(" test.i: %d\n",test.i);
  20.         printf(" test.pi:%.2f\n",test.pi);
  21.         printf("test.str:%s\n",test.str);
  22.         return 0;
  23. }
复制代码
最佳答案
2021-6-10 21:40:38
  1. $ ./main
  2. addr of test.i: 0xffffcc38
  3. addr of test.pi:0xffffcc38
  4. addr of test.str:0xffffcc38
  5. test.i: 1752394054
  6. test.pi:3.13
  7. test.str:FishC
复制代码

对 test 的最后一次赋值是 strcpy(test.str,"FishC");
所以 test.str:FishC 这个输出没问题,(共用体)union 就是共用一个位置,后一个覆盖前一个,只会保留最后一次赋值
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-6-10 21:40:38 | 显示全部楼层    本楼为最佳答案   
  1. $ ./main
  2. addr of test.i: 0xffffcc38
  3. addr of test.pi:0xffffcc38
  4. addr of test.str:0xffffcc38
  5. test.i: 1752394054
  6. test.pi:3.13
  7. test.str:FishC
复制代码

对 test 的最后一次赋值是 strcpy(test.str,"FishC");
所以 test.str:FishC 这个输出没问题,(共用体)union 就是共用一个位置,后一个覆盖前一个,只会保留最后一次赋值
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-6-10 23:13:18 | 显示全部楼层
公用一个内存啊(取最大的成员长度)  
会互相覆盖      
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-27 16:07

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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