错误:转换为请求的非标量类型

atb*_*atb 14 c malloc struct

我试图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;
Run Code Online (Sandbox Code Playgroud)

以下是我遇到问题的代码:

dungeon d1 = (dungeon) malloc(sizeof(dungeon));
Run Code Online (Sandbox Code Playgroud)

它给了我错误"错误:转换为非标量类型请求"有人可以帮助我理解为什么这是?

Car*_*rum 15

您不能将任何内容转换为结构类型.我认为你打算写的是:

dungeon *d1 = (dungeon *)malloc(sizeof(dungeon));
Run Code Online (Sandbox Code Playgroud)

但请不要malloc()在C程序中转换返回值.

dungeon *d1 = malloc(sizeof(dungeon));
Run Code Online (Sandbox Code Playgroud)

工作得很好,不会隐藏#include你的错误.

  • 如果你转换malloc()的返回值有什么问题? (3认同)