This is a pretty big question, so please take time to read and please provide an answer.
My question is, How can we take input as a String in C?
We normally ask the user to provide the number of characters, let's say n
and we can simply declare like char str[n]
. This will all be well and good.
But, when we normally declare a size like char str[100]
, etc. But if we provide a string let's say, of a length 20, then 80 bytes are getting wasted, we don't normally want that, is it ok to declare like that.
What if the user gives let's say a string of input 120, then only 100 characters will be stored in our character array, we don't want that either.
So, basically we don't know what a user may input. He inputs a string of length, his choice.
In the above cases, we take input using scanf
or gets
, like scanf("%s", str)
, scanf("%[^\n]%*c", str)
, scanf("%[^\n]s",str)
, gets(str)
, etc.
When we use scanf, when we input a string let's say of length 5 and when we give 6 characters, the 6th character won't get stored.
When we use puts, when we input a string let's say of length 5 and when we give 6 characters, the 6th character will get stored in the succesive byte, but the 6th character won't get displayed when we try to print. When we input 6 characters, it gives a message like 'stack smashing detected'. We don't know what other data is there, it may get overridden.
Is the above mentioned cases right or wrong, could you please help me?
Now, there is another way to declare String and take input as a string, we may use pointers, like we may dynamically allocate memory and then deallocate when our work with the string is finished. We use like, malloc
, calloc
, realloc
to allocate memory and free
to deallocate.
We may declare like char* str = (char*)malloc(size*sizeof(char))
and we take input as scanf("%[^\n]s",str)
. But here also, we need to provide the size. What if we don't know the size? What if the user provides input greater than the size?
We may also declare like char* str = (char*)malloc(sizeof(char))
. Here, when we input a string lets say of length 5. The string gets stored in the heap in consecutive bytes, but we have only allocated 1 byte, the remaining 4 bytes of our input is stored in a way that, it is basically illegal memory access, we can't do that, can we?
The above mentioned 2 cases are the same, is this right or wrong? Could you please help me?
I'm in a Zugzwang, chess terms. Could you please help me? What are the ways there to declare a string and take input without specifying the size? Can we dynamically allocate without specifying the size? What are all the ways to declare a string?