There are not many options. Basically you either allocate a sufficient amount for what you need or ask how much you want to allocate.
The second option really is terrible. From the usability point of view it doesn’t make any sense.
The first option has the disadvantage of possibly allocating more memory than actually needed. But who cares. This is no longer a problem on any kind of device unless you want to input really long text, but you wouldn’t do it simply anyway, in a long text you would have a data structure to manage it.
One might think that there is also the disadvantage of imposing a ceiling. But this is an advantage. Letting a user what is the maximum limit of text to type is the last thing the program should do. Again, if you need something more complex, you’ll 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 \0
printf("String: ");
scanf("%99s", ponteiro); //permite digitar um caractere a menos que o alocado
free(ponteiro);
return 0;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Now responses have appeared that show creative algorithms but that probably will be Overkill. My solution wastes memory, the others presented waste allocation time and in the commentary appeared one that wastes or two but in moderate quantities.
Have you noticed that there is no free lunch? You have to decide what you want to waste. In a simple example any can be wasted smoothly. I would use the occam’s razor and would keep the simplest. If I preferred the most complicated I would have posted it.
I could use an optimized version and better handled in more complex problems where I really was having memory problems and didn’t know the size of what I need in data input. I don’t have any of these problems ever so I never worried about it. I guess you shouldn’t either.
How is the user typing? Enter your code. Maybe your problem is somewhere else. But I can already say that you will have to allocate before receiving the information.
– Maniero
bigdown, at the moment the code looks like this: http://codepad.org/oqBIJKVG, but what I want is that the program does not ask how many bytes the user will use, but that the program after the user type the string, use strlen and calculate the number of characters typed and allocate them. Got it?
– Levi Ivanovsk
@Leviivanovsk For these and other reasons (object orientation, for example) I chose C++. And it gives many better results on Google. Take a look!
– user2692
@Leviivanovsk Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on all the posts on the site as well. Did any help you more? You need something to be improved?
– Maniero
boot malloc(sizeof(string)), this returns the size occupied in memory by the string variable
– BarrosKing