嵌套结构体初始化编译错误 error C2099: initializer is not a constant

初始化嵌套结构体变量错误
今天定义一个嵌套的结构体,编译报错如下
error C2099: initializer is not a constant
下面贴出错误代码

//typedef two struct types
typedef struct str0 {
char i;
}_def_str_0;

typedef struct str1{
char i;
_def_str_0 st;
}_def_str_1;

//initialize two structures
_def_str_0 str_0 = {
0,
};

_def_str_1 str_1 = {
0,
/*************Err line !!!*************/
str_0,
};

这里错误的原因是初始化变量时不能用变量(str_0)赋值,必须是常量。
上述结构体str_1 的正确初始化操作应该是

_def_str_1 str_1 = {
	0,
	{
		0,
	}
};

或者用结构体指针来实现。

//typedef two struct types
typedef struct str0 {
	char i;
}_def_str_0;

typedef struct str1{
char i;
	_def_str_0 *p_st;
}_def_str_1;

//initialize two structures
_def_str_0 str_0 = {
	0,
};

_def_str_1 str_1 = {
	0,
	&str_0,
};

猜你喜欢

转载自blog.csdn.net/qq_28851611/article/details/90739618