版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28877125/article/details/85244848
一、结构体基本初始化方法
定义
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;
}
这里通过