繁体   English   中英

初始化包含结构数组和 function 指针 c99 和 gnu99 的嵌套结构时出错

[英]Error initializing nested struct containing array of struct and function pointer c99 and gnu99

我在初始化包含两个成员的嵌套结构时出错

  • unsigned int
  • typedef void (*vfptr)(void); .

第一个结构或父结构仅包含两个变量,如下所示:

typedef struct Stype1 {
    unsigned int uiVar;
    vfptr  vfptr1;
}Stype1;

第二个结构包含上述结构作为结构数组:

typedef struct Stype2 {
    Stype1  Stype1inst[4];
}Stype2;

每当我尝试使用gcc 12.2.1进行编译时,我都会收到错误消息:

error: expected expression before ‘{’ token
   30 |     Stype2inst.Stype1inst[4] = {{1,(vfptr)Vfun1},

我还尝试使用此处提到的指定初始化来初始化结构:

typedef struct Stype2 {
    Stype1  Stype1inst[] = {
        {.uiVar = 1 , .vfptr1 = Vfun1 }
        };
}Stype2;

但我得到错误:

error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
   24 |     Stype1  Stype1inst[] = {
      |            

还尝试使用-std=gnu99-std=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.Stype1inst[4] = {{1,(vfptr)Vfun1},
                                {2,(vfptr)Vfun2},
                                {3,(vfptr)Vfun3},
                                {4,(vfptr)Vfun4}};
    return 0;
}

结构和 arrays 只能在声明时初始化。 在您的情况下, Stype2inst被声明为结构,因此初始化声明将采用以下形式:

Stype2 Stype2inst = { ... };

在这里, ...将是结构数据的初始值。 该数据是一个数组(有四个元素),因此我们现在可以将表单“扩展”为以下内容:

Stype2 Stype2inst = { { e0, e1, e2, e3 } };

每个元素( e0e3 )本身都是一个结构(类型为Stype1 ,并将采用您已正确使用的形式: {1,(vfptr)Vfun1} (尽管此处的强制转换是不必要的)。

将所有这些放在一起并添加换行符、空格和缩进以便于阅读,我们得到以下声明/初始化:

Stype2 Stype2inst = {   // Outer braces are for the "Stype2" structure
    {                   // Next are for the enclosed array of "Stype1"
        { 1, Vfun1 },   // Each of these is for one element/structure;
        { 2, Vfun2 },   
        { 3, Vfun3 },   // Note that you don't need the casts to vfptr
        { 4, Vfun4 }
    }
};

注意:尽管您在问题的评论中“尝试”过的更短的初始化形式(如下所示)是有效的,但它不清楚并且可能含糊不清:

Stype2 Stype2inst = { 1,(vfptr)Vfun1, 2,(vfptr)Vfun2, 3,(vfptr)Vfun3, 4,(vfptr)Vfun4 };

使用此语法,clang-cl 编译器生成以下诊断信息(四次):

警告:建议围绕子对象 [-Wmissing-braces] 的初始化使用大括号

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM