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.