메모리는 다음 두 가지 방법으로 할당할 수 있습니다. -

정적 메모리 할당
정적 변수는 고정된 크기의 할당된 공간의 한 블록에서 정의합니다. 한 번 할당되면 절대 해제할 수 없습니다.
프로그램에서 선언된 변수에 대해 메모리가 할당됩니다.
-
주소는 '&' 연산자를 사용하여 얻을 수 있으며 포인터에 할당할 수 있습니다.
-
메모리는 컴파일 시간에 할당됩니다.
-
메모리의 정적 할당을 유지하기 위해 스택을 사용합니다.
-
이 할당에서는 메모리가 한 번 할당되면 메모리 크기를 변경할 수 없습니다.
-
효율성이 떨어집니다.
변수의 최종 크기는 프로그램을 실행하기 전에 결정되며 이를 정적 메모리 할당이라고 합니다. 컴파일 타임 메모리 할당이라고도 합니다.
컴파일 타임에 할당되는 변수의 크기는 변경할 수 없습니다.
예시 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\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