c - Keeping the value of a String initialized into a function -
i know title isn't clear, clearer code + examples. want initialize char* ("motsecret" in main, "mot" in function) containing word selected randomly file, doing function. array made dynamic using memory allocation. variable in function initialized, when print value after exited function, value change , become "0@"
here part concerned in main :
int main() { file* dico =null; char *motsecret, *motres; char lettre=' '; int check=0, nbcoups=10, longueur=0, nbmots=0; bool erreur = true; srand(time(null)); nbmots = scandico(dico); getword(dico, nbmots, motsecret); printf("mot : %s", motsecret);
the problem appears after function getword(). here code of function :
void getword(file* dico, int nblignes, char *mot) { int nummotchoisi=rand() % nblignes, nbchar=0; char charactuel=' '; dico = fopen("dico.txt", "r"); rewind(dico); if(dico != null) { while (nummotchoisi > 0) { charactuel = fgetc(dico); if (charactuel == '\n') nummotchoisi--; } charactuel = ' '; while(charactuel != '\n') { charactuel = fgetc(dico); nbchar++; } fseek(dico,-(nbchar)-1,seek_cur); mot = malloc(nbchar * sizeof(char)); if(mot == null) { printf("probleme d'allocation memoire"); exit(0); } fgets(mot, size, dico); mot[strlen(mot) - 1] = '\0'; printf("mot = %s ", mot); } fclose(dico); }
the printf @ end of function return value, , printf after getword() in main show value changed in function haven't been "saved"...
other thing, works fine without memory allocation.
i hope i'm clear enough. if forgot tell or if need more informations, please tell me.
c uses pass value
in function parameter passing.
you need double pointer, void getword(file* dico, int nblignes, char **mot)
if want allocate memory inside function.
as cascased effect, printf("mot : %s", motsecret);
trying access uninitialized memory, causing undefined behaviour.
suggestions:
i see no reason use
file *dico
parameter ingetword()
. in can local.instead of using double pointer, recommend returning allocated pointer
getword()
, i.e., changevoid getword()
char * getword()
, addreturn mot
, usemotsecret = getword(<params>)
Comments
Post a Comment