Chinaunix首页 | 论坛 | 博客
  • 博客访问: 714149
  • 博文数量: 192
  • 博客积分: 2653
  • 博客等级: 少校
  • 技术积分: 1623
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-31 18:25
个人简介

How tough life is, how strong you should be!

文章分类

全部博文(192)

文章存档

2015年(1)

2014年(2)

2013年(37)

2012年(152)

分类: C/C++

2013-10-21 17:54:03

原文转自:http://blog.csdn.net/subkiller/article/details/6205939 

最近项目小组在去除代码中的warning,在修正代码的过程中看到了对结构体不正确的初始化方式:
假设有一个如下的struct定义:

struct   astruct
{
    int   a;
    int   b;
};
struct   astruct   test={0};

即使astruct中都是类型的成员这样的初始化话也是不正确的。
这种初始化仅仅是把a变量设置为了0,而未对b变量做初始化。
产生这样错误的原因,大概是收到数组初始化的影响。数组是可以这么初始化话的,而且初始化的值只能是0!
对结构体的初始化,可以有一下三种。

struct   test
{
    int   a;
    int   b;
};
int  main()
{
    struct   test   t1={0,0}; 
    struct   test   t2=
        .a=2
        .b=3
    };  
    struct  test   t3=
        a:12345,
        b:567890
    };  
    printf(“t1.a = %d, t1.b = %d/n”, t1.a, t1.b);
    printf(“t2.a = %d, t2.b = %d/n”, t2.a, t2.b);
    printf(“t3.a = %d, t3.b = %d/n”, t3.a, t3.b);
    return  0;
}

第一种使我们最常见的方式,2,3种方式应该是C99所支持的,但是在的编译器中不支持C99,所以才会给人以只有GCC支持的错觉。第一种方式尽量少写。在生成汇编代码时,会消耗掉非常多的时钟周期。

(二)

          驱动内核模块是不需要实现每个函数的。像卡的驱动就不需要从目录的结构 中读取数据。那么,相对应的file_operations重的项
就为 NULL。gcc还有一个方便使用这种结构体的扩展。你会在较现代的驱动内核模块中见到。 新的使用这种结构体的方式如下:
struct   file_operations   fops = {
        read: device_read,
        write: device_write,
        open: device_open,
        release: device_release
};
   
同样也有C99语法的使用该结构体的方法,并且它比GNU扩展更受推荐。我使用的版本为 2.95为了方便那些想移植你的代码的人,你最好使用这种语法。它将提高代码的兼容性:
struct   file_operations   fops = {
        .read = device_read,
        .write = device_write,
        .open = device_open,
        .release = device_release
};

(三)

#include
struct   date
{
    int   year;
    int   month;
    int   day;
};
void   main()
{
    //struct date time_1={time_1.year=2008,time_1.month=2,time_1.day=12}; //2008-2-12
    //struct date time_1={time_1.year=2008,time_1.day=12,time_1.month=2}; //2008-2-2
    //struct date time_1={time_1.month=2,time_1.year=2008,time_1.day=12}; //2008-2008-12
    //struct date time_1={time_1.month=2,time_1.day=12,time_1.year=2008}; //2008-12-2008
    //struct date time_1={time_1.day=12,time_1.year=2008,time_1.month=2}; //2008-2-2
    //struct date time_1={time_1.day=12,time_1.month=2,time_1.year=2008}; //2008-2-2008
    printf("%d-%d-%d/n",time_1.year,time_1.month,time_1.day);
}


用此种方式时,struct date time_1={time_1.year=2008,time_1.day=12,time_1.month=2};//2008-2-2
其初始化顺序不能调..

阅读(1057) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~