免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 5841 | 回复: 8
打印 上一主题 下一主题

结构体定义时初始化问题。 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-04-03 17:14 |只看该作者 |倒序浏览
今天发现结构体可以在定义时就初始化,自己写了个测试程序,代码如下

#include <stdio.h>
int main()
{
&nbsp;&nbsp;&nbsp;&nbsp;struct aa
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int b :10;
&nbsp;&nbsp;&nbsp;&nbsp;}a;
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;struct cc
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int d :10;
&nbsp;&nbsp;&nbsp;&nbsp;}c;
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;struct ee
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int f :10;
&nbsp;&nbsp;&nbsp;&nbsp;}e;
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;printf("a.b is: %d\n",a.b);
&nbsp;&nbsp;printf("c.d is: %d\n",c.d);
&nbsp;&nbsp;printf("e.f is: %d\n",e.f);
&nbsp;&nbsp;&nbsp;&nbsp;return 0;
}

运行结果如下:
a.b is: 4
c.d is: -452
e.f is: 248


运行结果很奇怪,本人不解,望得到坛友们的指点。

论坛徽章:
0
2 [报告]
发表于 2008-04-03 17:19 |只看该作者
who 和你说
    struct aa
    {
        int b :10;
    }a;
这样是初始化 ??  plz BAIDU 位域。

论坛徽章:
0
3 [报告]
发表于 2008-04-03 17:25 |只看该作者
哦,原来这样,那我去看看,谢谢了

论坛徽章:
0
4 [报告]
发表于 2008-04-03 17:30 |只看该作者
同问,我以前也以为这样可以初始化呢

论坛徽章:
0
5 [报告]
发表于 2008-04-03 17:31 |只看该作者
初始化是用.b=×××来完成的。

论坛徽章:
0
6 [报告]
发表于 2008-04-03 17:36 |只看该作者
原帖由 cugb_cat 于 2008-4-3 17:31 发表
初始化是用.b=×××来完成的。

不是唯一方式  

  1. 2 #include <stdio.h>
  2. 3
  3. 4 typedef struct{
  4. 5     short   a;
  5. 6     short   b;
  6. 7 }u_t;
  7. 8
  8. 9 int cc;
  9. 10
  10. 11 int main()
  11. 12 {
  12. 13     u_t     src = { 10, 100 };
  13. 14     u_t     dst = src;
  14. 15     printf( "a:%d,b:%d\n", dst.a, dst.b );
  15. 16     return 0;
  16. 17 }   
复制代码

论坛徽章:
0
7 [报告]
发表于 2008-04-04 05:18 |只看该作者

论坛徽章:
1
双子座
日期:2015-01-04 14:25:06
8 [报告]
发表于 2008-04-04 16:28 |只看该作者
LZ是猜的还是被人误导了

论坛徽章:
0
9 [报告]
发表于 2008-04-04 21:31 |只看该作者
受教了
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP