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

In C programming, what does static memory allocation mean?

王林
Release: 2023-09-14 15:21:01
forward
1031 people have browsed it

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]);
}
Copy after login

Output

Elements of the array are
1020304050
Copy after login

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);
}
Copy after login

Output

Sum of elements in the array is : 150
Product of elements in the array is : 12000000
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template