C 结构体初始化

1.前言

今天阅读linux kernel oom代码,看到一种结构体初始化方式,原来没见过,记录一下。

//结构体定义
struct oom_control {
	/* Used to determine cpuset */
	struct zonelist *zonelist;

	/* Used to determine mempolicy */
	nodemask_t *nodemask;

	/* Memory cgroup in which oom is invoked, or NULL for global oom */
	struct mem_cgroup *memcg;

	/* Used to determine cpuset and node locality requirement */
	const gfp_t gfp_mask;

	/*
	 * order == -1 means the oom kill is required by sysrq, otherwise only
	 * for display purposes.
	 */
	const int order;

	/* Used by oom implementation, do not set */
	unsigned long totalpages;
	struct task_struct *chosen;
	unsigned long chosen_points;
};
//初始化方式
struct oom_control oc = {
	.zonelist = NULL,
	.nodemask = NULL,
	.memcg = NULL,
	.gfp_mask = 0,
	.order = 0,
};

2.struct四种初始化的方式

初始化方式1: 定义时赋值(不可乱序,不可缺省)
初始化方式2: 定义后赋值
初始化方式3: 定义时赋值(可乱序 可缺省. 点号)
初始化方式4: 定义时赋值(可乱序 可缺省 : 冒号)

//测试代码
#include <stdlib.h>
#include <stdio.h>

struct test_struct {

	int    a;
	char*   p;
};

int main()
{
	struct test_struct imp;
	imp.a = 100;
	imp.p = "hello world100";

	struct test_struct imp0 = {
		.a = 0,
		.p = "hello world0"
		};
	struct test_struct imp1 = {
		a : 1,
		p : "hello world1"
	};
	struct test_struct imp2 = {2, "hello world2"};

	printf("imp  a:%d  p: %s\n", imp.a, imp.p);
	printf("imp0 a:%d  p: %s\n", imp0.a, imp0.p);
	printf("imp1 a:%d  p: %s\n", imp1.a, imp1.p);
	printf("imp2 a:%d  p: %s\n", imp2.a, imp2.p);
	
	return 0;
}

3.总结

相比顺序初始化而言,乱序初始化成员可以不按照顺序初始化,而且可以只初始化部分成员,乱序初始化有两种方式,一种是用点(.)符号,一种是用冒号(:)。

参考:https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html

此条目发表在C/C++分类目录,贴了标签。将固定链接加入收藏夹。

发表评论

您的电子邮箱地址不会被公开。