簡體   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