malloc()
ฟังก์ชัน malloc() ใช้เพื่อจัดสรรขนาดไบต์ที่ร้องขอ และส่งคืนตัวชี้ไปยังไบต์แรกของหน่วยความจำที่จัดสรร ส่งคืนตัวชี้ null หากล้มเหลว
นี่คือไวยากรณ์ของ malloc() ในภาษา C
pointer_name = (cast-type*) malloc(size);
ที่นี่
-
ชื่อตัวชี้ − ชื่อใดๆ ที่กำหนดให้กับตัวชี้
-
ประเภทนักแสดง − ประเภทข้อมูลที่คุณต้องการส่งหน่วยความจำที่จัดสรรโดย malloc()
-
ขนาด − ขนาดของหน่วยความจำที่จัดสรรเป็นไบต์
นี่คือตัวอย่าง malloc() ในภาษา C
ตัวอย่าง
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
if(p == NULL) {
printf("\nError! memory not allocated.");
exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
return 0;
} ผลลัพธ์
นี่คือผลลัพธ์
Enter elements of array : 32 23 21 8 Sum : 84
ฟรี()
ฟังก์ชัน free() ใช้เพื่อจัดสรรคืนหน่วยความจำที่จัดสรรโดย malloc() โดยจะไม่เปลี่ยนค่าของตัวชี้ซึ่งหมายความว่ายังคงชี้ไปยังตำแหน่งหน่วยความจำเดิม
นี่คือไวยากรณ์ของ free() ในภาษา C
void free(void *pointer_name);
ที่นี่
-
ชื่อตัวชี้ − ชื่อใดๆ ที่กำหนดให้กับตัวชี้
นี่คือตัวอย่าง free() ในภาษา C
ตัวอย่าง
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
if(p == NULL) {
printf("\nError! memory not allocated.");
exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
free(p);
return 0;
} ผลลัพธ์
นี่คือผลลัพธ์
Enter elements of array : 32 23 21 28 Sum : 104