문제
동적 메모리 할당 함수를 사용하여 요소를 표시하고 추가하는 C 프로그램을 작성하십시오.
해결책
C에서 라이브러리 함수 malloc 런타임에 메모리 블록을 바이트 단위로 할당합니다. 할당된 메모리의 기본 주소를 가리키는 void 포인터를 반환하고 메모리를 초기화하지 않은 상태로 둡니다.
구문
void *malloc (size in bytes)
예를 들어,
-
정수 *ptr;
ptr =(int * ) malloc(1000);
-
정수 *ptr;
ptr =(int * ) malloc(n * sizeof(int));
참고 − 메모리가 비어 있지 않으면 NULL을 반환합니다.
예시
#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 45 65 12 23 The sum of elements is 168 Displaying the cleared out memory location : 10753152 0 10748240 0 23