There are not many options. Basically, you either allocate enough of what you need or ask how much you want to allocate.
The second option really is terrible. From a usability point of view, it makes no sense.
The first option has the disadvantage of possibly allocating more memory than is really necessary. But who cares. This is not a problem anymore on any kind of device unless you want to get really long text, but you would not do it in a simple way anyway, in a long text it would have a data structure to manage it. p>
Someone may think that there is also the disadvantage of imposing a ceiling. But this is an advantage. Letting a user what the maximum limit of text to type is the last thing the program should do. Again, if you need something more complex, you will need a more complex program.
So the solution is to do this:
#include <stdio.h>
#include <stdlib.h>
int main(){
char *ponteiro = malloc(100); //um caractere será ocupado pelo terminador #include <stdio.h>
#include <stdlib.h>
int main(){
char *ponteiro = malloc(100); //um caractere será ocupado pelo terminador %pre%
printf("String: ");
scanf("%99s", ponteiro); //permite digitar um caractere a menos que o alocado
free(ponteiro);
return 0;
}
printf("String: ");
scanf("%99s", ponteiro); //permite digitar um caractere a menos que o alocado
free(ponteiro);
return 0;
}
See running on ideone .
Now there are answers that show creative algorithms but that will probably be overkill . My solution wastes memory, the others presented waste allocation time, and in the comet appeared one wastes or two but in moderate amounts.
Realized that there is no free lunch. You have to decide what you want to waste. In a simple example any can be wasted without problems. I would use the Occam's razor and I would stick with the simpler one. If I preferred the more complicated one I would have posted it.
I could use an optimized and better-handled version of more complex problems where I was really having memory problems and did not know the size of what I need in data entry. I do not have any of these problems ever so I never bothered about it. I do not think you should either.