免费注册 查看新帖 |

Chinaunix

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

结构体初始化的方法 file_operations初始化 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-12-22 08:51 |只看该作者 |倒序浏览
最近项目小组在去除代码中的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 <stdio.h>
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);
}

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

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP