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,*/
};

      下面,运行这个测试程序,验证上述说法:


最新文章

  1. 篇三:MySQL分页
  2. sublime text 2 快捷键
  3. MySQL - 问题集 - &quot;Waiting for table metadata lock&quot;(待完善)
  4. 如何防止ElasticSearch集群出现脑裂现象(转)
  5. hadoop2.6完全分布式安装HBase1.1
  6. Django对静态文件的处理——部署阶段
  7. 【QT】找茬外挂制作
  8. LDF文件过大的解决办法
  9. Jvascript方法
  10. memcached+狀態模式+工廠方法使用
  11. WCF、WebAPI、WCFREST、WebService之间的区别和选择
  12. Python 编程规范
  13. freemarker demo
  14. Linux下阅读源代码工具安装
  15. windows7安装docker
  16. 集合02_Queue
  17. SharePoint Online 设置网站集
  18. block(四)揭开神秘面纱(下)-b
  19. VIM的自动补全
  20. centos7.3安装zip,unzip

热门文章

  1. BZOJ2023: [Usaco2005 Nov]Ant Counting 数蚂蚁
  2. 2015第19周四jquery版本
  3. POJ2367 Genealogical tree (拓扑排序)
  4. [置顶] API相关工作过往的总结之Sandcastle简要使用介绍
  5. MergeSort 归并排序
  6. poj 1328 Radar Installation(贪心)
  7. class 类(1)
  8. js为鼠标添加右击事件
  9. JMeter简单的性能测试实例
  10. 为iPhone 6设计自适应布局