在 C++ 中使用 new 和 delete 運算子
new 運算子
new 運算子請求在堆中分配記憶體。如果可用記憶體充足,它會將記憶體初始化為指標變數,然後返回其地址。
以下是 C++ 語言中 new 運算子的語法:
pointer_variable = new datatype;
以下是初始化記憶體的語法:
pointer_variable = new datatype(value);
以下是分配一個記憶體塊的語法:
pointer_variable = new datatype[size];
以下是在 C++ 語言中使用 new 運算子的示例:
示例
#include <iostream>
using namespace std;
int main () {
int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(223.324);
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] << " ";
}
return 0;
}輸出
Value of pointer variable 1 : 28 Value of pointer variable 2 : 223.324 Value of store in block of memory: 11 12 13 14 15
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP