Linux2.6内核 -- 结构的初始化

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

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


原文地址:https://www.cnblogs.com/james1207/p/3281525.html