C++ 中的 delete() 和 free()
delete()
delete 運算子用於釋放記憶體。使用者可以使用此 delete 運算子釋放已建立的指標變數。
以下是 C++ 語言中 delete 運算子的語法:
delete pointer_variable;
以下是刪除已分配記憶體塊的語法:
delete[ ] pointer_variable;
以下是 C++ 語言中 delete 運算子的示例:
示例
#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()
free() 函式用於釋放由 malloc() 分配的記憶體。它不會更改指標的值,這意味著它仍然指向相同的記憶體位置。
以下是 C 語言中 free() 的語法:
void free(void *pointer_name);
這裡:
pointer_name − 指標的任何名稱。
以下是 C 語言中 free() 的示例:
示例
#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);
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP