Why do we need the array to be dynamic. It must be cleared to me other I am unable to know the basic concept
Why did we use dynamic array is not clear yet!
I would like to explain you through an example:
lets say user has given us n integers as input and we need to sort these integers.
n will be known to us at run time. how will you create array?
well, you can waste memory by taking an array of max size possible. but if our machine has limited memory, its better to take array of size n. that is dynamic array.
thanks
a more detailed explanation can be:
-
There are two types of memory.
One is the static memory or the compile-time memory that is used for variables and arrays declared in the program , those which the compiler can identify and allocate memory at runtime.
int a;
int b[1000];
int b[n]; -
The second memory is the heap memory or the dynamic memory. It can only be allocated at the runtime. There are various ways to allocate dynamic memory such as by using C functions like alloc( ) , calloc( ) etc. or by using the C++ ‘new’ operator.
int* a = new int[100];
int n=1000;
int* a = new int[n]; -
in both ways you can create an array of variable size or fixed size. but the later method using new has variety of uses than first one. you can deallocate the memory created by new by using delete. this might not seem useful to you but in memory limited environment, its very useful.
-
Not every question can always be solved using static array. There are much more complex data structures than array like Trees and Linked Lists that you will learn later in this course. All of them use dynamic memory allocation.
suggest to read:
please rate and resolve if satisfied.
thanks
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.