错误:转换为非标量类型请求
问题描述:
我遇到了一个小问题,试图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));
它给我的错误“错误:转换到非标量型请求“ 有人可以帮我理解这是为什么吗?
答
您不能将任何东西投射到结构类型。我想你的意思是写的是:
dungeon *d1 = (dungeon *)malloc(sizeof(dungeon));
但请不要在C程序投下的malloc()
返回值。
dungeon *d1 = malloc(sizeof(dungeon));
将工作得很好,不会隐藏#include
错误从你。
答
通过malloc
分配的内存必须存储在一个指向对象的指针,而不是对象本身:
dungeon *d1 = malloc(sizeof(dungeon));
答
malloc
返回一个指针,那么可能是你想要的是以下几点:
dungeon* d1 = malloc(sizeof(dungeon));
下面是malloc的样子:
void *malloc(size_t size);
正如你可以看到它返回void*
,但是你shouldn't cast the return value。
如果您施放malloc()的返回值,会出现什么问题? – 2013-04-23 05:27:22
@PriteshAcharya,现代编译器可能没有太多。这就是说,这是非惯用的。阅读[这个问题及其答案](http://*.com/questions/605845/do-i-cast-the-result-of-malloc)进行大量的详细讨论。 – 2013-04-23 05:31:57
'struct student_simple { \t int rollno; \t char * name; };' 'struct student_simple * s2 = malloc(sizeof(struct student_simple *));struct student_simple * s3 = malloc(sizeof(struct student_simple));' 我可以同时使用s2和s3,但没有任何问题,但是当我检查gdb的大小时012dbgdb $''p sizeof(struct student_simple)'给出16 gdb $'p sizeof(struct student_simple *)'给出8 8字节的malloc如何存储student_simple结构。 – 2013-04-23 05:49:09