2012-03-05 57 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()的返回值,會出現什麼問題? – 2013-04-23 05:27:22

+0

@PriteshAcharya,現代編譯器可能沒有太多。這就是說,這是非慣用的。閱讀[這個問題及其答案](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)進行大量的詳細討論。 – 2013-04-23 05:31:57

+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(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

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

相關問題