-1
Good afternoon. I would like to know how to allocate a string dynamically in C without asking the user the size of the string. Just putting it to write the string.
-1
Good afternoon. I would like to know how to allocate a string dynamically in C without asking the user the size of the string. Just putting it to write the string.
1
You can do this by creating a custom function to read string and read dynamically:
char *ler_string(char *nome)
{
int i = 0;
char letra;
nome = malloc(sizeof(char));
do
{
letra = getchar();
if(letra != '\n')
{
nome[i] = letra;
i++;
nome = realloc(nome, sizeof(char) * i+1);
}
}while(letra != '\n');
nome[i] = '\0';
return nome;
}
The above function reads a string and allocates its size as it finds a character other than enter in the input buffer. Example of use in main:
char *nome;
printf("Digite seu nome: ");
nome = ler_string(nome);
printf("Seu nome eh: %s \n", nome);
free(nome);
return 0;
Note that you are setting the terminator character ' 0' out of of the allocated area for nome
. Either way, although inefficient for consecutive relocations, it is a good solution for strings of undefined size.
Actually, I fixed the ' 0' error now.
0
You can’t guess, can you? But what you can do is allocate from a size that you think will be enough and after it type the string you realoca it to the size actually used.
int main()
{
char *st = (char*) malloc(5000);
printf("Informe a sua string");
scanf("%s", st); //supondo que a string não vai ter espaços;
st = realloc(strlen(st) + 1);
}
Browser other questions tagged c c++11
You are not signed in. Login or sign up in order to post.
Hello Giovanne, in the title you are talking about C++, in the body of your question you talk about C and the question is marked with tags of C#, C and C++. These are different languages with different Apis for reading strings from standard input.
– Anthony Accioly