Home > OS >  Why do I get several errors using typedef in C?
Why do I get several errors using typedef in C?

Time:12-29

I am trying to define TrapLevelLayout as the equivalent of a two-dimentional array of TrapSquare defined above. This is my snippet of code:

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

This code produces the following warning and errors:

./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;
                      ^
                      ;

Can someone explain me what is wrong with my code?

CodePudding user response:

Well there are few issues:

  1. Using same name as typedef TrapSquare in structure definition
  2. typedef (TrapSquare[32][18]) TrapLevelLayout; wrong declaration
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

CodePudding user response:

This answer is an alternative/extension to the correct answer.

You can use a popular typeof extension (a feature in C23):

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