2012-03-05 9 views
10

से अनुरोध किया गया है मुझे इस संरचना को मॉलोक करने का प्रयास करने में एक छोटी सी समस्या है। यहाँत्रुटि: गैर-स्केलर प्रकार में रूपांतरण

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)); 

लेकिन एक सी कार्यक्रम में malloc() के रिटर्न मान डाली न करें।

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

ठीक काम करेगा और आप से #include कीड़े छिपा नहीं होगा।

+2

यदि आप malloc() के वापसी मूल्य को डालते हैं तो समस्या क्या है? –

+0

@ प्रितेश आचार्य, शायद आधुनिक कंपाइलरों के साथ ज्यादा नहीं। उसने कहा, यह गैर-मूर्खतापूर्ण है। विस्तृत चर्चा के लिए [इस सवाल और इसके उत्तरों] पढ़ें (http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)। –

+0

'struct student_simple { \t int rollno; \t char * name; }; ' 'स्ट्रक्चर student_simple * s2 = malloc (sizeof (struct student_simple *)) के बीच क्या अंतर है; संरचना student_simple * s3 = malloc (sizeof (struct student_simple)); ' मैं बिना किसी समस्या के एस 2 और एस 3 दोनों का उपयोग करने में सक्षम हूं लेकिन जब मैं gdb gdb $' p sizeof (struct student_simple) में आकार की जांच करता हूं तो 16 देता है gdb $ 'p sizeof (struct student_simple *) '8 देता है 8 बाइट्स का मॉलोक छात्र_सिंपल संरचना को कैसे संग्रहीत करता है। –

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