c - Filling struct with data in file -


i'm trying fill struct data of file.

the file separated double dot this:

string1:15 

when read file , fill fields of struct data segmentation fault.

here struct file character.h:

#ifndef character_h_ #define character_h_  typedef struct character *personaje;  struct character{         char name[20];         int lvl; };   extern void savecharacter(char *name, int lvl); extern personaje *getcharacter(); extern char *tostring(personaje *pj); #endif 

and here function in source file character.c:

personaje *getcharacter(){         file *fp;         personaje *salida = (personaje*) malloc(sizeof(personaje));         fp = fopen("kprct", "rb");          fscanf(fp, "%[a-za-z]:%d", (*salida)->name, &((*salida)->lvl));         printf("linea: %s : %d\n", (*salida)->name, (*salida)->lvl);          fclose(fp);         return salida;  } 

how can fill struct file data?

hint: not typecast pointer struct, stuct itself. less confusing , avoid problem facing here: allocate space pointer, not struct.

also defining character **:

personaje *salida = (personaje*) malloc(sizeof(personaje)); 

so: given type definitions:

personaje salida = malloc(sizeof(*salida)); 

note: using *salida in sizeof makes term independent type of salida.

the rest of code broken, functions have 1 * whereever personaje involved.

a proper definition be:

typedef struct {         char name[20];         int lvl; } personaje;     // or name type character 

then, prototypes, use personaje * have. malloc-line be:

personaje *salida = malloc(sizeof(*salida)); 

(note: did not have change sizeof()-argument.)

additional issues:

  • always check results of system functions, might report error. malloc might return null, file functions might report error, too.
  • always restrict number of chars fscanf reads char array! now, invitation buffer overflow, aka undefined behaviour.
  • do not cast void * used malloc, free, etc.

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -