본문 바로가기
코딩/C++

동적할당(new, delete)

by sonysame 2024. 3. 8.

1. 동적할당

#include <iostream>

using namespace std;

int main() {
	int* ptr = new int{ 7 };

	//이미 메모리를 다 쓰고 있어서 에러날 경우, 예외처리 -> std::nothrow로 nullptr이 들어감
	//int * ptr = new (std::nothrow)int{ 7 };
	
	cout << ptr << endl;
	cout << *ptr << endl;

	delete  ptr;
	ptr = nullptr;

	if(ptr != nullptr) {
		cout << ptr << endl;
		cout << *ptr << endl;
	}
	return 0;
}

new -> delete 필요!

메모리 할당으로 다 써버렸을 때는, std::nothrow로 예외처리 가능

 

 

2. 동적할당배열

#include <iostream>

using namespace std;

int main(){
	int length;
	cin >> length;

	int* array = new int[length](); //으로 초기화
	//int* array2 = new int[6] {11, 22, 33, 44, 55, 66}; 
	array[0] = 1;
	array[1] = 2;

	for (int i = 0; i < length; i++) {
		cout << (uintptr_t) & array[i] << endl;
		cout << array[i] << endl;
	}
	delete[] array;

	return 0;
}

'코딩 > C++' 카테고리의 다른 글

참조 변수 Reference Variable  (0) 2024.03.09
const 포인터  (0) 2024.03.09
문자열 const char *  (0) 2024.03.08
포인터  (0) 2024.03.07
구조체  (0) 2024.03.06