Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++의 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

위의 프로그램에서는 4개의 변수가 선언되었고 그 중 하나는 malloc에 ​​의해 할당된 메모리를 저장하는 포인터 변수 *p입니다. 배열의 요소는 사용자에 의해 인쇄되고 요소의 합이 인쇄됩니다. 할당된 메모리를 삭제하려면 delete ptr1, delete pt2 및 delete[] ptr3을 사용합니다.

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;