ปัญหา
วิธีแสดงและคำนวณผลรวมของ n ตัวเลข โดยใช้ฟังก์ชันจัดสรรหน่วยความจำแบบไดนามิกในภาษา C?
วิธีแก้
โปรแกรม C แสดงองค์ประกอบและคำนวณผลรวมของ n ตัวเลขโดยผู้ใช้ โดยใช้ฟังก์ชันจัดสรรหน่วยความจำแบบไดนามิก ที่นี่เรายังพยายามลดการสูญเสียหน่วยความจำ
ตัวอย่าง
#include <stdio.h>
#include <stdlib.h>
void main() {
// ประกาศตัวแปร พอยน์เตอร์ และผลรวม //
int numofe, i, sum = 0;
int *p;
// อ่านจำนวนองค์ประกอบจากผู้ใช้ //
printf("Enter the number of elements : ");
scanf("%d", &numofe);
// เรียกฟังก์ชัน malloc() //
p = (int *)malloc(numofe * sizeof(int));
/* พิมพ์เอาต์พุท - ต้องใช้ if เพราะต้องตรวจสอบว่าหน่วยความจำจัดสรรสำเร็จหรือไม่ */
if (p == NULL) {
printf("Memory not available");
exit(0);
}
// พิมพ์องค์ประกอบ //
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); // ล้าง 2 ตำแหน่งหน่วยความจำแรก
printf("\nDisplaying the cleared out memory location : \n");
for(i = 0; i < numofe; i++) {
printf("%d\n", p[i]); // จะแสดงค่าขยะ
}
}ผลลัพธ์
เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:
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