문제
C 언어에서 동적 메모리 할당 기능을 사용하여 n개의 숫자의 합을 표시하고 계산하는 방법은 무엇입니까?
해결책
다음은 동적 메모리 할당 함수를 사용하여 사용자가 요소를 표시하고 n개의 합을 계산하는 C 프로그램입니다. 여기서도 메모리 낭비를 줄이려고 합니다.
예시
#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: 4 Enter the elements: 23 45 67 89 The sum of elements is 224 Displaying the cleared out memory location: 7410816 0 7405904 0