在 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