I have this code
int e;
scanf("%d",&e);
int ar[e];
is this dynamic allocation? It really looks like it is as I can allocate memory at run time.
I used this to get input from user for the number of elements and then filling it again by the user.
I have this code
int e;
scanf("%d",&e);
int ar[e];
is this dynamic allocation? It really looks like it is as I can allocate memory at run time.
I used this to get input from user for the number of elements and then filling it again by the user.
This is not exactly dynamic memory allocation, as generally understood for the sense of the term.
This is called variable length array. The array size is known at run-time only and hence memory is allocated at run-time.
However, unlike the dynamic memory allocation library functions (malloc()
/ calloc()
), the underlying memory allocation is compiler-dependent. For example, gcc
allocates VLAs in stack.
Thus, the major difference in this approach (compared to dynamic memory alocation) is, the VLAs reside in automatic storage. Once you leave the scope, it is no longer available. Quoting C11
, chapter §6.2.4
For such an object that does have a variable length array type, its lifetime extends from the declaration of the object until execution of the program leaves the scope of the declaration. [...]
FWIW, this was introduced in C99
standard, only to be made optional in C11
.
And AFAIK, C++
does not support this as integral part of the standard, it may be available as a compiler extension.
int ar[e]
is a stack-allocated VLA(variable-length array), which is invalid in C++, but does work in C99. When the block ends, it will automatically be popped (deallocated).
Though the memory is allocated at run-time in this case, it is not exactly dynamic memory allocation. And keep in mind that dynamically allocated memory should be released/freed after its usages.
It should be like this (in C)
int e;
scanf("%d", &e);
/*dynamically allocate memory using malloc function*/
int* ar = (int*) malloc(e * sizeof(int));
...
...
...
/* release memory using free() function */
free(ar);