I have been curious to know How to decide string length ?
When I asked my teacher this, he replied "you have to assume a value and allocate to srting".
which eventually pushed me to my original question how to assume a specific length for a string. I used to think about memory allocation, i.e We are usually write
char str[50] = "Hello world";
Here compiler allocates 50 bytes of memory for string
str
but only 10 bytes will be used and remaining 40 byte is wasted.
So is there any way to allocate memory after user inputs the string?
We used to give input about 20 to 30 input max so remaining are wasted
That's right. There's no limit to how much you can allocate, but if you know that you won't need more than a certain amount, then you can just allocate that much. Usually for a Hello World running on a modern PC you're not strapped for memory, but if you store millions of records with names and so on in a database, it's good to think about memory consumption.
I even asked teachers is there any way that I can decler array size dynamically so that he replied answer "No" please help
You can allocate memory dynamically. Suppose you have code like this:
int n = 30;
char *string = malloc(n);
free(string); // any memory allocated with malloc should be freed when it is not used anymore
Now string
has a size of 30
because that's what n
was set to, but it could be anything else, determined at runtime. It could be something that the user has inputted.
In C++ there's a construct called std::string
that automatically does the dynamic memory allocation for you. You can do something like
std::string s = "Hello";
s += " World";
And you don't even have to worry about memory allocation. If it doesn't fit internally, it will reallocate the memory on its own with an amortized constant runtime.