funcion void not return changing vector | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
0

funcion void not return changing vector

I've been writing this function. It worked fine writing it with return. Now i'm trying to convert it into void. Sytax seems to be right and in fact the function works, but the vector isn't passed into the main. The code is the following: void flip(char *frase){ int num = (int)strlen(frase); char* frase2=malloc(num*sizeof(char)); int i; for (i = num-1; i >= 0 ; i--){ frase2[(num-1)-i] = frase[i]; } printf("frase 1 %s", frase); frase=frase2; printf("\nfrase2 ĆØ %s", frase2); } int main(){ char frase[50]; fgets(frase, 50, stdin); flip(frase); printf("%s\n", frase); return 0; }

3rd Apr 2021, 5:37 PM
Cristopher Ricciotti
Cristopher Ricciotti - avatar
1 Resposta
+ 3
I don't know how far you are in your study of pointers, but the problem here is that the pointer `frase` is being copied as you call the function. In your `flip` function you assign to `frase` but this doesn't affect the original `frase` outside the function. Consider this simpler example: void floop(int x) { x = 4; } int x = 3; floop(x); // x is still 3 So you've two options: Either, pass a pointer to frase: void flip(char** pfrase){ char* frase = *pfrase; ... } char** pfrase = &frase; flip(pfrase); Or, since you are dealing with strings, you can also strcpy frase2 into frase. (Probably the better solution.) // instead of frase=frase2 strcpy(frase, frase2);
3rd Apr 2021, 5:49 PM
Schindlabua
Schindlabua - avatar