在 C 编程中,什么是静态内存分配?
内存可以按照以下两种方式分配 −

静态内存分配
静态变量在一个已分配空间块中定义,且大小固定。一旦分配,就永远不能释放。
内存为程序中声明的变量分配。
可使用“&”运算符获取地址,并可以将其分配给指针。
内存是在编译时分配的。
它使用栈来维护内存的静态分配。
在这种分配中,一旦分配了内存,内存大小就无法更改。
它的效率较低。
在运行程序之前就决定变量的最终大小,这将称为静态内存分配。它也称为编译时内存分配。
我们不能更改在编译时分配的变量的大小。
示例 1
静态内存分配通常用于数组。让我们看一个关于数组的示例程序 −
#include<stdio.h>
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 1020304050
示例 2
让我们考虑另一个示例,计算数组中所有元素的总和和乘积 −
#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
",sum);
printf("Product of elements in the array is : %d
",product);
}输出
Sum of elements in the array is : 150 Product of elements in the array is : 12000000
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP