エラー: 非スカラー型への変換が要求されました 質問する

エラー: 非スカラー型への変換が要求されました 質問する

この構造体を malloc しようとすると、ちょっとした問題が発生します。構造体のコードは次のとおりです。

typedef struct stats {                  
    int strength;               
    int wisdom;                 
    int agility;                
} stats;

typedef struct inventory {
    int n_items;
    char **wepons;
    char **armor;
    char **potions;
    char **special;
} inventory;

typedef struct rooms {
    int n_monsters;
    int visited;
    struct rooms *nentry;
    struct rooms *sentry;
    struct rooms *wentry;
    struct rooms *eentry;
    struct monster *monsters;
} rooms;

typedef struct monster {
    int difficulty;
    char *name;
    char *type;
    int hp;
} monster;

typedef struct dungeon {
    char *name;
    int n_rooms;
    rooms *rm;
} dungeon;

typedef struct player {
    int maxhealth;
    int curhealth;
    int mana;
    char *class;
    char *condition;
    stats stats;
    rooms c_room;
} player;

typedef struct game_structure {
    player p1;
    dungeon d;
} game_structure;

問題のあるコードは次のとおりです。

dungeon d1 = (dungeon) malloc(sizeof(dungeon));

「エラー: 非スカラー型への変換が要求されました」というエラーが表示されます。なぜこのようになるのか、誰か教えてくれませんか?

ベストアンサー1

構造体型にキャストすることはできません。おそらく次のように書きたかったのでしょう:

dungeon *d1 = (dungeon *)malloc(sizeof(dungeon));

malloc()ただし、 C プログラムではの戻り値をキャストしないでください。

dungeon *d1 = malloc(sizeof(dungeon));

問題なく動作し、#includeバグを隠すことはありません。

おすすめ記事