I researched a lot of static and dynamic memory allocation but still, there is a confusion that:
int n, i, j;
printf("Please enter the number of elements you want to enter:\t");
scanf("%d", &n);
int a[n];
for (i = 0; i < n; i++)
{
printf("a[%d] : ", i + 1);
scanf("%d", &a[i]);
}
Does int a[n]
come under static or dynamic memory allocation?
The C standard does not talk about dynamic allocation (or static allocation, for that matter). But it does define storage durations: static, automatic, thread and allocated. Which dictates how long an object (a piece of data) lives (is usable).
Static in the sense of storage duration means the object is usable for the entire execution of the program. Variables at file scope ('global' variables), and local variables with
static
in their declaration, have static storage duration.Automatic storage duration are your regular local variables, they live only for the duration of the block they are declared in (the function, or inside the curly braces of e.g. a
for
loop).Allocated storage duration refers to memory obtained via
malloc
and friends. It is available from a (successful) call tomalloc
, until a corresponding callfree
. This is often referred to as dynamic memory allocation, as it is a way to obtain a block of memory with the size determined at run-time.Your variable
a
has automatic storage duration. However, it can be considered dynamic in the sense that its length is determined at run-time, rather than compile-time. Just like allocated storage duration has.