ปัญหา
ค้นหาผลรวมของ n หมายเลขที่ผู้ใช้ป้อนโดยใช้หน่วยความจำที่จัดสรรแบบไดนามิกโดยใช้การเขียนโปรแกรม C
วิธีแก้ปัญหา
การจัดสรรหน่วยความจำแบบไดนามิกช่วยให้โปรแกรมเมอร์ C สามารถจัดสรรหน่วยความจำได้ในขณะใช้งานจริง
ฟังก์ชันต่างๆ ที่เราใช้ในการจัดสรรหน่วยความจำแบบไดนามิก ณ รันไทม์คือ −
- malloc () - จัดสรรบล็อกของหน่วยความจำเป็นไบต์ที่รันไทม์
- calloc () - จัดสรรบล็อกต่อเนื่องของหน่วยความจำ ณ รันไทม์
- realloc () - ใช้เพื่อลด (หรือ) ขยายหน่วยความจำที่จัดสรร
- ฟรี () - จัดสรรพื้นที่หน่วยความจำที่จัดสรรไว้ก่อนหน้านี้
โปรแกรม 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