Home >Backend Development >C++ >In C programming, what does static memory allocation mean?

In C programming, what does static memory allocation mean?

王林
王林forward
2023-09-14 15:21:011060browse

Memory can be allocated in the following two ways:

In C programming, what does static memory allocation mean?

Static memory allocation

Static variables are defined in an allocated space block with a fixed size. Once allocated, it cannot be released.

Allocate memory for declared variables in the program.

  • You can use the "&" operator to get the address and assign it to the pointer.

  • Memory is allocated at compile time.

  • It uses the stack to maintain static allocation of memory.

  • In this kind of allocation, once the memory is allocated, the memory size cannot be changed.

  • Low efficiency.

The final size of the variable is determined before the program runs, which is called static memory allocation. Also known as compile-time memory allocation.

We cannot change the size of variables allocated at compile time.

Example 1

Static memory allocation is usually used for arrays. Let’s do a sample program taking an array as an example:

Demonstration

#include<stdio.h>
main (){
   int a[5] = {10,20,30,40,50};
   int i;
   printf (&ldquo;Elements of the array are&rdquo;);
   for ( i=0; i<5; i++)
      printf (&ldquo;%d, a[i]);
}

Output

Elements of the array are
1020304050

Example 2

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

Real-time demonstration

#include<stdio.h>
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//
   for(i=0;i<5;i++){
      //Calculating sum and product, printing output//
      sum=sum+array[i];
      product=product*array[i];
   }
   //Displaying sum and product//
   printf("Sum of elements in the array is : %d</p><p>",sum);
   printf("Product of elements in the array is : %d</p><p>",product);
}

Output

Sum of elements in the array is : 150
Product of elements in the array is : 12000000

The above is the detailed content of In C programming, what does static memory allocation mean?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete