how to write a name using pointers

1

I need a program that uses heap memory to store any name. we have the number of characters in the name and then the name, for example:

32

Josefina Penacho Reis dos Santos

The output should be the name, in this case:

Josefina Penacho Reis dos Santos

My program is as follows:

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]='
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]='%pre%';                        //final da string

    aux = vetor;

    for(;*aux != '%pre%';aux++)
    {
        printf("%c",*aux);                  //printar o nome 
    }

    printf("\n");

    return 0;
}
'; //final da string aux = vetor; for(;*aux != '%pre%';aux++) { printf("%c",*aux); //printar o nome } printf("\n"); return 0; }

I have no idea where the error is, please help me !! Thanks

    
asked by anonymous 05.06.2015 / 00:15

1 answer

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

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

  • The 'malloc' takes up space; if you're going to read a four-character name, you need five bytes (so you need to straighten the line with scanf(" %[^\n]", &var) ):

    +---+---+---+---+----+
    | j | o | s | e | 
    +---+---+---+---+----+
    | j | o | s | e | %pre% |
    +---+---+---+---+----+
    
    | +---+---+---+---+----+
  • To read lines with spaces in between, you should use " %s" ; fgets reads one word at a time (and even the version with the brackets fails if the line can start with a blank space - in that case, the only alternative is to fscanf in of a buffer and %code% on top of that buffer, which is much more complicated.)

  • 05.06.2015 / 00:23