1
I need a program that uses memory heap to store any name. input we have the number of characters of the name and then the name, for example:
32
Josefina Penacho Reis dos Santos
The output must be the name, in this case:
Josefina Penacho Reis dos Santos
My program is the following:
int main(void)
{
char *vetor=NULL; //vetor é o nome da pessoa
int tam; //tam é o numero de caracteres do nome (tamanho do espaço alocado)
char *aux; //vetor auxiliar
scanf("%d\n", &tam); //determinar o tamanho do espaço alocado
vetor=(char*) malloc(tam*sizeof(char)); //alocar o espaço necessario
vetor[tam]='\0'; //final da string
aux = vetor;
for(;*aux != '\0';aux++)
{
printf("%c",*aux); //printar o nome
}
printf("\n");
return 0;
}
I have no idea where the mistake is, help me pf!! Thank you
Thanks for the tip! A part is solved, the problem now is that even if there is a surname, the program only prints the first name :/
– Bruno Ascacibas
I updated the answer to treat this case - you can update the question to mention that it is possible that the name has spaces in the middle?
– user25930
OK. The scanf(" %[ n}", &var) has solved the problem. Thank you!
– Bruno Ascacibas
Instead of the
scanf()
suggest thefgets()
to read lines.– pmg