새 연산자
new 연산자는 힙에 메모리 할당을 요청합니다. 사용 가능한 메모리가 충분하면 포인터 변수에 메모리를 초기화하고 해당 주소를 반환합니다.
다음은 C++ 언어의 새 연산자 구문입니다.
pointer_variable = new datatype;
다음은 메모리를 초기화하는 구문입니다.
pointer_variable = new datatype(value);
다음은 메모리 블록을 할당하는 구문입니다.
pointer_variable = new datatype[size];
다음은 C++ 언어에서 새 연산자의 예입니다.
예시
#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
삭제 연산자
삭제 연산자는 메모리 할당을 해제하는 데 사용됩니다. 사용자는 이 삭제 연산자에 의해 생성된 포인터 변수의 할당을 해제할 수 있는 권한이 있습니다.
다음은 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