1. 程式人生 > >C語言--結構體初始化

C語言--結構體初始化

一、結構體基本初始化方法

定義

	struct Mystruct {
		int first;
		double second;
		char* third;
		float four;
	};

1、方法一:定義時賦值

賦值時注意定義時各個成員的順序,不能錯位。

	struct Mystruct test = {99, 3.1415, "hello world", 0.35};

2、方法二:定義後逐個賦值

這種方法無所謂順序。

	struct Mystruct test;
	
	test.first = 99;
	test.second = 3.1415
; test.third = "hello world"; test.four = 0.35;

3、方法三:定義時亂序賦值(C語言風格–C99標準)

這種方法結合了第一種和第二種方法,既能初始化賦值,也可以不考慮順序。學校裡面沒有教過,但是進入社會後這種方法很常見。

	struct Mystruct test = {
	    .second = 3.1415,
		.first = 99,
		.four = 0.35,
		.third = "hello world"
	};

4、方法四:定義時亂序賦值(C++風格–GCC擴充套件)

這種方法和第三種類似,也不考慮順序,類似鍵-值對的方式。

	struct Mystruct test = {
		second:3.1415,
		first:99,
		four:0.35,
		third:"hello world"
	};

二、結構體進階使用

定義

//函式指標
typedef int(*func_cb)(int a, int b);

//結構體定義 
typedef struct _struct_func_cb_ {
	int a;
	int b;
	func_cb func;
} struct_func_cb_t;

//加法函式定義 
int do_func_cb(int a, int b)
{
	return (
a + b); }

使用

int main(void)
{
	int ret = 0;
	//順序初始化結構體1 
	struct_func_cb_t func_cb_one = { 10, 20, do_func_cb };
	//亂序初始化結構體2 
	struct_func_cb_t func_cb_two = {
		.b = 30,
		.a = 20,
		.func = &do_func_cb,
	};

	ret = func_cb_one.func(func_cb_one.a, func_cb_one.b);
	printf("func_cb_one func: ret = %d\n", ret);
	
	ret = func_cb_two.func(func_cb_two.a, func_cb_two.b);
	printf("func_cb_two func: ret = %d\n", ret);

	return 0;
}

這裡通過