1
// FUNCAO //
char *nome(char text[20])
{
char *n;
int n2;
int n3 = 0;
printf("%s\n",text);
while((n2 = getchar()) != '\n' && n2 != EOF)
{
if(n3 < 1)
{
n = (char*) malloc(sizeof(char));// alocando 1 bytes
*n = n2;// posicao 0 e = letra digitada
n3++; // encrementando 1 pra sair da condicao if
}
// Daqui pra frente só realoca //
n3++;
n = (char*) realloc(n, n3*sizeof(char));
*(n+(n3-1)) = n2;
}
return n;// retorna o ponteiro
}
//Usando a funcao //
char *name = nome("Nome:");// texto antes de digitar o nome
for(int i = 0; i < 5; i++) // ignora i < 5 ainda vo mexer aqui
printf("%c", *(name+i)); // mostra o nome
free(name);
it worked out to start the pointer as null and then just relocate, but I didn’t understand it very well, it has how to explain this vlw business better
– LavaiBala
There’s a better way to ask this business?
– Maniero
why start as null ? has an explanation
– LavaiBala
Because there the relocation occurs from nothing (the null one) to somewhere. So the effect is the same as the
malloc(), it allocates something new, but since it has nothing to dislocate, everything works as expected, thus eliminating the exception in the algorithm.– Maniero
vlw help, and pro loop I used: for (int i = 0; i < strlen(name); i++){ show}
– LavaiBala
https://answall.com/q/167528/101 I wouldn’t do that. I wouldn’t use a loop.
– Maniero
to having a problem with while when I use the free() it gives an error, already without the free it goes normal, very strange
– LavaiBala
This seems to be another problem, ask a question with details so we can help.
– Maniero