C99/GNU99下含结构体数组与函数指针的嵌套结构体初始化报错
嵌套结构体数组初始化错误解决
问题根源分析
你遇到的两个编译错误,核心原因如下:
赋值语句误用初始化语法:
你在main函数中写的Stype2inst.Stype1inst[4] = {{...}};存在两个问题:Stype1inst[4]是数组的第5个元素(C数组下标从0开始,你的数组仅有4个元素,合法下标范围是0-3),属于越界访问;- C语言中,大括号
{}的初始化语法仅能用于变量声明阶段,不能在后续的赋值语句中使用。
结构体类型定义中直接初始化成员:
在struct Stype2定义里写Stype1 Stype1inst[] = {...};是非法的——结构体类型定义只是描述数据结构的模板,不能直接给成员赋值,必须在定义该类型的变量时进行初始化操作。
正确的解决方案
以下是几种可行的写法,可根据你的需求选择:
方案1:全局变量直接初始化
由于Stype2inst是全局变量,可以在声明时直接完成初始化:
#include <stdio.h> typedef void (*vfptr)(void); void Vfun1(){}; void Vfun2(){}; void Vfun3(){}; void Vfun4(){}; typedef struct{ unsigned int uiVar; vfptr vfptr1; }Stype1; typedef struct{ Stype1 Stype1inst[4]; }Stype2; // 全局变量声明时直接初始化 Stype2 Stype2inst = { .Stype1inst = { {1, Vfun1}, {2, Vfun2}, {3, Vfun3}, {4, Vfun4} } }; int main() { // 直接使用已初始化的变量 return 0; }
方案2:函数内局部变量初始化
如果把Stype2inst作为main函数的局部变量,同样可以在声明时完成初始化:
#include <stdio.h> typedef void (*vfptr)(void); void Vfun1(){}; void Vfun2(){}; void Vfun3(){}; void Vfun4(){}; typedef struct{ unsigned int uiVar; vfptr vfptr1; }Stype1; typedef struct{ Stype1 Stype1inst[4]; }Stype2; int main() { // 局部变量声明时初始化 Stype2 Stype2inst = { .Stype1inst = { {1, Vfun1}, {2, Vfun2}, {3, Vfun3}, {4, Vfun4} } }; return 0; }
方案3:函数内逐个元素赋值
如果必须给已声明的全局/局部变量赋值,可以逐个初始化数组元素:
#include <stdio.h> typedef void (*vfptr)(void); void Vfun1(){}; void Vfun2(){}; void Vfun3(){}; void Vfun4(){}; typedef struct{ unsigned int uiVar; vfptr vfptr1; }Stype1; typedef struct{ Stype1 Stype1inst[4]; }Stype2; Stype2 Stype2inst; int main() { // 逐个赋值数组元素,使用复合字面量(C99及以后支持) Stype2inst.Stype1inst[0] = (Stype1){1, Vfun1}; Stype2inst.Stype1inst[1] = (Stype1){2, Vfun2}; Stype2inst.Stype1inst[2] = (Stype1){3, Vfun3}; Stype2inst.Stype1inst[3] = (Stype1){4, Vfun4}; return 0; }
方案4:函数内用复合字面量整体赋值
C99及以后标准支持用复合字面量给整个结构体变量赋值:
#include <stdio.h> typedef void (*vfptr)(void); void Vfun1(){}; void Vfun2(){}; void Vfun3(){}; void Vfun4(){}; typedef struct{ unsigned int uiVar; vfptr vfptr1; }Stype1; typedef struct{ Stype1 Stype1inst[4]; }Stype2; Stype2 Stype2inst; int main() { // 用复合字面量给整个结构体赋值 Stype2inst = (Stype2){ .Stype1inst = { {1, Vfun1}, {2, Vfun2}, {3, Vfun3}, {4, Vfun4} } }; return 0; }
内容的提问来源于stack exchange,提问作者Gaurav Pathak
相关产品推荐
相关产品推荐

