Linux2.6内核 -- 结构的初始化
2024-10-18 23:34:36
Linux 内核中用到了大量的结构体,在编码规范中也给出了结构体初始化的规则,这篇文章中有对其的解释:http://blog.csdn.net/dlutbrucezhang/article/details/10296897,不过,这篇文章中并没有给出实例分析,下面我写了一段测试程序:
#include<stdio.h>
#include<string.h> struct test {
int test_value1;
float test_value2;
char *test_value3;
}; int main(void)
{
int i;
char my_name[] = "DLUTBruceZhang";
char my_school[] = "DLUT"; for(i = 0; i < 2; i++){
if (i % 2 == 0){
struct test my_test = {
.test_value1 = 10,
.test_value2 = 10.0,
.test_value3 = my_name,
};
printf("test_value1 = %d, test_value2 = %f,\
test_value3 = %s\n", my_test.test_value1,
my_test.test_value2, my_test.test_value3); } else {
struct test my_test = {
.test_value1 = 100,
.test_value2 = 100.0,
.test_value3 = my_school,
};
printf("test_value1 = %d, test_value2 = %f,\
test_value3 = %s\n", my_test.test_value1,
my_test.test_value2, my_test.test_value3);
}
}
struct test my_test = {
/*.test_value1 = 10,*/
/*.test_value2 = 10.0,*/
/*.test_value3 = my_name,*/
};
printf("test_value1 = %d, test_value2 = %f,\
test_value3 = %s\n", my_test.test_value1,
my_test.test_value2, my_test.test_value3); return 0;
}
分析:
1.首先给出结构体的定义,它包含三个字段,一个整型,一个浮点型,一个字符指针
struct test {
int test_value1;
float test_value2;
char *test_value3;
};
2.两次赋初值,根据情况不同,对其进行赋值,赋值方法采用的是 Linux 内核编码规范中的方法(这里忽略了标识符)
struct test my_test = {
.test_value1 = 10,
.test_value2 = 10.0,
.test_value3 = my_name,
};
struct test my_test = {
.test_value1 = 100,
.test_value2 = 100.0,
.test_value3 = my_school,
};
3.不赋初值的情况是整型默认为 0,浮点型默认为 0.0,字符指针默认为 NULL
struct test my_test = {
/*.test_value1 = 10,*/
/*.test_value2 = 10.0,*/
/*.test_value3 = my_name,*/
};
下面,运行这个测试程序,验证上述说法:
最新文章
- 篇三:MySQL分页
- sublime text 2 快捷键
- MySQL - 问题集 - ";Waiting for table metadata lock";(待完善)
- 如何防止ElasticSearch集群出现脑裂现象(转)
- hadoop2.6完全分布式安装HBase1.1
- Django对静态文件的处理——部署阶段
- 【QT】找茬外挂制作
- LDF文件过大的解决办法
- Jvascript方法
- memcached+狀態模式+工廠方法使用
- WCF、WebAPI、WCFREST、WebService之间的区别和选择
- Python 编程规范
- freemarker demo
- Linux下阅读源代码工具安装
- windows7安装docker
- 集合02_Queue
- SharePoint Online 设置网站集
- block(四)揭开神秘面纱(下)-b
- VIM的自动补全
- centos7.3安装zip,unzip