2012-03-05 13 views
10

Tengo un pequeño problema al intentar malloc esta estructura. Aquí es el código de la estructura:Error: Conversión a tipo no escalar solicitado

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; 

Y aquí está el código que estoy teniendo un problema con:

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

Me da el error "Error: la conversión al tipo no escalar pedido " ¿Alguien puede ayudarme a entender por qué es esto?

Respuesta

12

No se puede convertir nada a un tipo de estructura. Lo que supongo que significa que escribir es:

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

Pero por favor, no rechaces el valor de retorno de malloc() en un programa C.

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

funciona muy bien y no ocultar #include errores de usted.

+2

¿cuál es el problema si arroja el valor de retorno de malloc()? –

+0

@PriteshAcharya, probablemente no mucho con los compiladores modernos. Dicho eso, no es idiomático. Lea [esta pregunta y sus respuestas] (http://stackoverflow.com/questions/605845/doi-i-cast-the-result-of-malloc) para mucha discusión detallada. –

+0

'struct student_simple { \t int rollno; \t char * name; }; ' ¿Cuál es la diferencia entre ' struct student_simple * s2 = malloc (sizeof (struct student_simple *)); struct student_simple * s3 = malloc (sizeof (struct student_simple)); ' Puedo usar tanto s2 como s3 sin ningún problema pero cuando compruebo el tamaño en gdb gdb $' p sizeof (struct student_simple) 'da 16 gdb $ 'p sizeof (struct student_simple *)' da 8 ¿cómo un malloc de 8 bytes almacena la estructura student_simple.? –

0

La memoria asignada por malloc se debe almacenar en un puntero a un objeto, no en el objeto mismo:

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

malloc devuelve un puntero, así que probablemente lo que quiere es la siguiente:

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

Esto es lo que se ve como malloc:

void *malloc(size_t size); 

Como puede ver, devuelve void*, sin embargo, shouldn't cast the return value.

Cuestiones relacionadas