为什么在C中使用typedef会出现几个错误?

pcww981p  于 2022-12-29  发布在  其他
关注(0)|答案(2)|浏览(196)

我尝试将TrapLevelLayout定义为上面定义的TrapSquare的二维数组的等价物,这是我的代码片段:

typedef struct TrapSquare {
    uint8_t x;
    uint8_t y;
    
    TrapBlock **blocks;
    uint8_t count;
} TrapSquare; //Definition of type TrapSquare

typedef (TrapSquare[32][18]) TrapLevelLayout; // Definition of TrapLevelLayout
                                              // as an array of TrapSquare

此代码将生成以下警告和错误:

./Headers/TrapTypes.h:111:21: error: expected ')'
typedef (TrapSquare[32][18]) TrapLevelLayout;
                   ^
./Headers/TrapTypes.h:111:9: note: to match this '('
typedef (TrapSquare[32][18]) TrapLevelLayout;
        ^
./Headers/TrapTypes.h:111:10: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
typedef (TrapSquare[32][18]) TrapLevelLayout;
~~~~~~~  ^
./Headers/TrapTypes.h:111:10: error: typedef redefinition with different types ('int' vs 'struct TrapSquare')
./Headers/TrapTypes.h:109:3: note: previous definition is here
} TrapSquare;
  ^
./Headers/TrapTypes.h:111:24: error: expected ';' after top level declarator
typedef (TrapSquare[32][18]) TrapLevelLayout;
                      ^
                      ;

有人能解释一下我的代码出了什么问题吗?

irtuqstp

irtuqstp1#

有几个问题:
1.在结构定义中使用与typedef TrapSquare相同的名称

  1. typedef (TrapSquare[32][18]) TrapLevelLayout;错误声明
typedef struct _TrapSquare {
    uint8_t x;
    uint8_t y;
    TrapBlock **blocks;
    uint8_t count;
} TrapSquare; //Definition of type TrapSquare

TrapSquare TrapLevelLayout [32][18];  // Definition of TrapLevelLayout
                                      // as an array of TrapSquare
ndasle7k

ndasle7k2#

此答案是correct answer的替代/扩展。
您可以使用流行的typeof扩展(C23中的一个特性):

typedef typeof(TrapSquare[32][18]) TrapLevelLayout;

相关问题