结构体的三种初始化方法

 最近项目小组在去除代码中的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);
}


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值