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运算符取消分配创建的指针变量的特权。

这是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