Error: Conversion to non-scalar type requested

佐手、 提交于 2019-12-31 20:14:34

问题


I'm having a small problem trying to malloc this struct. Here is the code for the structure:

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;

And here is the code I'm having a problem with:

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

It gives me the error "error: conversion to non-scalar type requested" Can someone help me understand why this is?


回答1:


You can't cast anything to a structure type. What I presume you meant to write is:

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

But please don't cast the return value of malloc() in a C program.

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

Will work just fine and won't hide #include bugs from you.




回答2:


malloc returns a pointer, so probably what you want is the following:

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

Here is what malloc looks like:

void *malloc( size_t size );

As you can see it return void*, however you shouldn't cast the return value.




回答3:


The memory assigned by malloc must be stored in a pointer to an object, not in the object itself:

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


来源:https://stackoverflow.com/questions/9561306/error-conversion-to-non-scalar-type-requested

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!