What do you mean by static memory allocation in C programming?

CServer Side ProgrammingProgramming

Memory can be allocated in the following two ways −

Static Memory Allocation

Static variable defines in one block of allocated space, of a fixed size. Once it is allocated, it can never be freed.

Memory is allocated for the declared variable in the program.

  • The address can be obtained by using ‘&’ operator and can be assigned to a pointer.

  • The memory is allocated during compile time.

  • It uses stack for maintaining the static allocation of memory.

  • In this allocation, once the memory is allocated, the memory size cannot change.

  • It is less efficient.

The final size of a variable is decided before running the program, it will be called as static memory allocation. It is also called compile-time memory allocation.

We can't change the size of a variable which is allocated at compile-time.

Example 1

Static memory allocation is generally used for an array. Let’s take an example program on arrays −

 Live Demo

main (){
   int a[5] = {10,20,30,40,50};
   int i;
   printf (“Elements of the array are”);
   for ( i=0; i<5; i++)
      printf (“%d, a[i]);


Elements of the array are

Example 2

Let’s consider another example to calculate sum and product of all elements in an array −

 Live Demo

void main(){
   //Declaring the array - run time//
   int array[5]={10,20,30,40,50};
   int i,sum=0,product=1;
   //Reading elements into the array//
   //For loop//
      //Calculating sum and product, printing output//
   //Displaying sum and product//
   printf("Sum of elements in the array is : %d\n",sum);
   printf("Product of elements in the array is : %d\n",product);


Sum of elements in the array is : 150
Product of elements in the array is : 12000000
Updated on 09-Mar-2021 08:33:58