我在尝试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));
它给出了错误“错误:转换为请求的非标量类型” 有人可以帮我理解为什么会这样吗?
答案 0 :(得分:14)
您无法将任何内容转换为结构类型。我认为你打算写的是:
dungeon *d1 = (dungeon *)malloc(sizeof(dungeon));
但请不要将malloc()
的返回值强制转换为C程序。
dungeon *d1 = malloc(sizeof(dungeon));
工作正常,不会隐藏#include
个错误。
答案 1 :(得分:2)
malloc
返回一个指针,所以你想要的是以下内容:
dungeon* d1 = malloc(sizeof(dungeon));
这是malloc的样子:
void *malloc( size_t size );
您可以看到它返回void*
,但是shouldn't cast the return value。
答案 2 :(得分:0)
malloc
分配的内存必须存储在指向对象的指针中,而不是存储在对象本身中:
dungeon *d1 = malloc(sizeof(dungeon));