How do I create a variable of type char with an indeterminate size [duplicate]

0

How do I create a variable of type char * (to store a name) with an indeterminate size?

Example:

char nome[30] = { 0 } // 30 é o valor máximo e no caso se a pessoa tiver um nome grande? que ultrapasse 30?
cout << "Informe seu nome completo: " << endl;
fgets(nome, 29, stdin);
    
asked by anonymous 15.10.2017 / 14:37

1 answer

1

Typically, arrays of sufficiently large static sizes, such as 999 cells, are used for performance reasons. However, in C ++ it has a high-level feature: stream. Flows allow you to add values bit by bit, without worrying about size (outside the architecture support). The use of class stringstream (in the <sstream> library) allows to form and then to generate a string structure, it can be seen as a const char* .

In C, I think stream would have to be implemented by hand. There are several ways to do this. Another option you have is to control the lifetime of the data, including using blocks to limit the lifetime of local variables. So you can create an amazing-sized array, copy it to a smaller one, and erase it. So, for example.

# include <stdio.h>
# include <stdlib.h>
int main( int argCount , char **argVector ){
   int tamanhoDoNome , indice ;
   char *nome ;
   {
      char nomeTemporario[999] = {0} ;
      cout << "Informe seu nome completo: " << endl ;
      fgets( nomeTemporario , 998 , stdin ) ;
      for( tamanhoDoNome=0 ; nomeTemporario[tamanhoDoNome++] ; ) ;
      nome = malloc( tamanhoDoNome*sizeof(char) ) ;
      for( indice=0 ; indice<tamanhoDoNome ; indice++ ) nome[indice]=nomeTemporario[indice] ;
   }
   // Agora não existem mais nomeTemporario e suas células, ficou nem a carcaça de sobra.
   free( nome ) ;
   // Agora não existem mais as células de nome, só existe a variável, ficou só a carcaça!
   return 0 ;
}

Any questions?

    
15.10.2017 / 16:43