Something simpler than this to allocate a typed text dynamically?

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);
    
asked by anonymous 19.06.2017 / 03:20

1 answer

1

There are minor improvements that can be made to the code, mostly just cosmetic, stylistic, and the like, even for readability that is bad.

You could put a null character at the end to become a string and it would not need the loop to print the string . Whichever is wrong, the only solution to resolve the size to be printed is the null character or also to return the size somehow. In fact, 5 is wrong.

Note that you are unlikely to want to leave unlimited entry. And there is usually nothing wrong with allocating the maximum value that the string can be input. Even if the maximum is a little too large, you can still optimize the allocations.

It is common to start with a minimum size, type 16, 64, 256 or even more. And double up the allocation with realloc() whenever you pop the capacity. You have to control the occupied size and confront with the total capacity to decide to relocate.

In addition, sizeof(char) is always 1, so this is unnecessary, cast (char*) is unsuitable in C.

You do not need to make the first allocation as an exception in if , realloc() is enough from the start pointer to null.

    
19.06.2017 / 03:42