2012-03-05 81 views
10

この構造体を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)); 

要求しました " これがなぜこれを理解するのを助けることができますか?

答えて

12

構造タイプには何もキャストできません。

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

しかし、Cプログラムでmalloc()の戻り値をキャストしないでください。私はあなたが書くためのものと推定することです。

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

はうまく動作しますし、あなたから#includeバグを隠しません。

+2

malloc()の戻り値をキャストするとどうなりますか? –

+0

@PriteshAcharya、現代のコンパイラではあまりないでしょう。つまり、それは非慣用的です。詳細な議論については、[この質問とその回答](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)を参照してください。 –

+0

'struct student_simple { \t int rollno; \t char * name; }; ' の違いは何ですか?struct student_simple * s2 = malloc(sizeof(struct student_simple *)); struct student_simple * s3 = malloc(sizeof(student student_simple)); s2とs3の両方を問題なく使用できますが、gdbでサイズをチェックすると、 gdb $ 'p studentof struct student_simple ' gdb $ 'p sizeof(struct student_simple *)'は8を返します 8バイトのmallocはstudent_simple構造をどのように格納しますか? –

0

mallocによって割り当てられたメモリがないオブジェクト自体には、オブジェクトへのポインタに格納する必要があります。

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

mallocは、ポインタを返すので、おそらく何をしたいことは、次のとおりです。

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

malloc関数は次のようになります。

void *malloc(size_t size); 

ご覧のとおり、void*ですが、shouldn't cast the return valueです。

関連する問題