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 to malloc
, until a corresponding call free
. 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.
int a[n]
is a variable length array with the automatic storage duration,
Consider the following demonstrative program.
#include <stdio.h>
#include <string.h>
int main(void)
{
const size_t N = 10;
for ( size_t i = 1; i <= N; i++ )
{
char s[i];
memset( s, '*', sizeof( s ) );
printf( "%*.*s\n", ( int )i, ( int )i, s );
}
return 0;
}
Its output is
*
**
***
****
*****
******
*******
********
*********
**********
Each time when the control is passed to the body of the loop the generated by the compiler code creates a local array s[n]
life-time of which ends at the end of the body of the loop.
No it's comes under automatic allocation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With