문제
C 프로그래밍을 사용하여 동적으로 할당된 메모리를 사용하여 사용자가 입력한 n개의 숫자의 합을 찾습니다.
해결책
동적 메모리 할당을 통해 C 프로그래머는 런타임에 메모리를 할당할 수 있습니다.
런타임에 동적으로 메모리를 할당하는 데 사용한 다양한 기능은 다음과 같습니다. -
- malloc() - 런타임에 메모리 블록을 바이트 단위로 할당합니다.
- calloc() - 런타임에 연속적인 메모리 블록을 할당합니다.
- realloc() - 할당된 메모리를 축소(또는) 확장하는 데 사용됩니다.
- free() - 이전에 할당된 메모리 공간을 할당 해제합니다.
다음 C 프로그램은 요소를 표시하고 n개의 숫자의 합을 계산하는 것입니다.
동적 메모리 할당 기능을 사용하여 메모리 낭비를 줄이려고 합니다.
예시
#include<stdio.h>
#include<stdlib.h>
void main(){
//Declaring variables and pointers,sum//
int numofe,i,sum=0;
int *p;
//Reading number of elements from user//
printf("Enter the number of elements : ");
scanf("%d",&numofe);
//Calling malloc() function//
p=(int *)malloc(numofe*sizeof(int));
/*Printing O/p -
We have to use if statement because we have to check if memory
has been successfully allocated/reserved or not*/
if (p==NULL){
printf("Memory not available");
exit(0);
}
//Printing elements//
printf("Enter the elements : \n");
for(i=0;i<numofe;i++){
scanf("%d",p+i);
sum=sum+*(p+i);
}
printf("\nThe sum of elements is %d",sum);
free(p);//Erase first 2 memory locations//
printf("\nDisplaying the cleared out memory location : \n");
for(i=0;i<numofe;i++){
printf("%d\n",p[i]);//Garbage values will be displayed//
}
} 출력
Enter the number of elements : 5 Enter the elements : 23 34 12 34 56 The sum of elements is 159 Displaying the cleared out memory location : 12522624 0 12517712 0 56