I want to read input from user using C program. I don't want to use array like,
char names[50];
because if the user gives string of length 10, then the remaining spaces are wasted.
If I use character pointer like,
char *names;
then I need to allocate memory for that in such a way of,
names = (char *)malloc(20 * sizeof(char));
In this case also, there is a possibility of memory wastage.
So, what I need is to dynamically allocate memory for a string which is of exactly same as the length of the string.
Lets assume,
If the user input is "stackoverflow"
, then the memory allocated should be of 14
(i.e. Length of the string = 13 and 1 additional space for '\0').
How could I achieve this?
Here's a snippet which I wrote which performs the same functionality.
This code is similar to the one written by Kunal Wadhwa.
You can also use a regular expression, for instance the following piece of code:
will get the whole line from stdin, allocating dynamically the amount of space that it takes. After that, of course, you have to free
names
.Below is the code for creating dynamic string :
This is more simple approach
This is a function snippet I wrote to scan the user input for a string and then store that string on an array of the same size as the user input. Note that I initialize j to the value of 2 to be able to store the '\0' character.
In main(), you can declare another char* variable to store the return value of dynamicstring() and then free that char* variable when you're done using it.