how to write a name using pointers

Asked

Viewed 350 times

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

1 answer

2

  1. It’s confusing, but unlike printf, in the scanf you nay should try to consume the \n of the entrance. scanf is a function full of subtleties, but a good rule if you do not want to think too much is always write " %d", " %s", etc. in the format specification, with a space just before the %, and none at the end of the string.

  2. You only have one scanf in your code; you are reading the string length but not the string itself.

  3. The '\0' takes up space; if you are going to read a four-character name, you need to five bytes (and therefore you need to set the line with the malloc):

    +---+---+---+---+----+
    | j | o | s | e | \0 |
    +---+---+---+---+----+
    
  4. To read lines with spaces in the middle, you must use scanf(" %[^\n]", &var); the " %s" reads one word at a time (and even the version with the brackets fails if the line can get started with a blank space - in this case, the only alternative is to do fgets into a buffer and fscanf on top of that buffer, which is much more complicated).

  • 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 :/

  • 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?

  • OK. The scanf(" %[ n}", &var) has solved the problem. Thank you!

  • Instead of the scanf() suggest the fgets() to read lines.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.