ลบ()
ตัวดำเนินการลบใช้เพื่อจัดสรรคืนหน่วยความจำ ผู้ใช้มีสิทธิ์จัดสรรคืนตัวแปรตัวชี้ที่สร้างขึ้นโดยตัวดำเนินการลบนี้
นี่คือไวยากรณ์ของตัวดำเนินการ delete ในภาษา C++
delete pointer_variable;
นี่คือรูปแบบการลบบล็อกของหน่วยความจำที่จัดสรร
delete[ ] pointer_variable;
นี่คือตัวอย่างของตัวดำเนินการลบในภาษา C++
ตัวอย่าง
#include <iostream>
using namespace std;
int main () {
int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(299.121);
int *ptr3 = new int[28];
*ptr1 = 28;
cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;
if (!ptr3)
cout << "Allocation of memory failed\n";
else {
for (int i = 10; i < 15; i++)
ptr3[i] = i+1;
cout << "Value of store in block of memory: ";
for (int i = 10; i < 15; i++)
cout << ptr3[i] << " ";
}
delete ptr1;
delete ptr2;
delete[] ptr3;
return 0;
} ผลลัพธ์
Value of pointer variable 1 : 28 Value of pointer variable 2 : 299.121 Value of store in block of memory: 11 12 13 14 15
ในโปรแกรมข้างต้น มีการประกาศตัวแปรตัวชี้สามตัวเป็น ptr1, ptr2 และ ptr3 ตัวแปรพอยน์เตอร์ ptr1 และ ptr2 เริ่มต้นด้วยค่าโดยใช้ new() และ ptr3 จะจัดเก็บบล็อกที่จัดสรรของหน่วยความจำด้วยฟังก์ชัน new()
int *ptr1 = NULL; ptr1 = new int; float *ptr2 = new float(299.121); int *ptr3 = new int[28]; *ptr1 = 28;
องค์ประกอบของอาร์เรย์ถูกพิมพ์โดยผู้ใช้และพิมพ์ผลรวมขององค์ประกอบ ในการลบหน่วยความจำที่จัดสรร มีการใช้ delete ptr1, delete pt2 และ delete[] ptr3
delete ptr1; delete ptr2; delete[] ptr3;
ฟรี()
ฟังก์ชัน 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
ในโปรแกรมข้างต้น มีการประกาศตัวแปรสี่ตัวและหนึ่งในนั้นคือตัวแปรตัวชี้ *p ซึ่งจัดเก็บหน่วยความจำที่จัดสรรไว้
int n = 4, i, *p, s = 0; p = (int*) malloc(n * sizeof(int));
องค์ประกอบของอาร์เรย์ถูกกำหนดโดยผู้ใช้และผลรวมของค่าจะถูกพิมพ์ออกมา รหัสเพื่อเพิ่มตัวชี้เป็นดังนี้ -
free(p);