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

本文解析了在C/C++中初始化嵌套结构体时遇到的常见错误:使用变量而非常量进行初始化。通过示例代码,展示了正确的初始化方法,包括直接初始化和使用结构体指针两种方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

初始化嵌套结构体变量错误
今天定义一个嵌套的结构体,编译报错如下
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,
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值