1.先定义再初始化
struct obj_t {
const char *name;
int val;
};
obj_t obj;
obj.name = "ABC";
obj.val = 0;
2.定义的时候初始化
struct {
const char *name;
int val;
} obj_2 = {"ABD", 0};
struct {
const char *name;
int val;
} obj_3 = {.name = "ABD", .val = 0};
struct obj_t {
const char *name;
int val;
};
obj_t obj_1 = {.name = "name", .val = 0};
3.结构体嵌套
struct {
const char *name;
int val;
struct{
int a;
}obj;
} obj_4 = {"ABD", 0, 666};
struct {
const char *name;
int val;
struct{
int a;
}obj;
} obj_5 = {.name = "ABD", .val = 0, {.a = 666}};
4.结构体数组
struct {
const char *name;
int val;
} obj_6[2] = {[0] = {"name 0", 0}, [1]= {"name 1", 1}};
5.结构体嵌套数组
struct {
const char *name;
int val;
struct{
int a;
}obj;
} obj_7[2] = {[0] = {"name 0", 0, 0}, [1] = {"name 1"}};
struct obj_t {
const char *name;
int val;
struct {
int a;
} obj;
};
obj_t obj_8[2] = {
[0] = {"name 0", 0, 0},
[1] = {"name 1", 0, 0}
};
6.使用类型别名
typedef struct {
const char *name;
int val;
} obj_t;
obj_t obj_9;
7.成员函数
void fn() {
;
}
typedef struct {
const char *name;
int val;
void (*function)();
} obj_t;
obj_t obj_10 = {.function = fn};