5.1 new / delete Operator and Dynamic Memory in C++

sunghoon·2025년 3월 15일
0

2.0 Glove Project

목록 보기
14/35
post-thumbnail

5.1.1 necessity need “Dynamic Memory”

we can't use Variable in Memory Size

#include <iostream>
using namespace std;

int main() {
    int nLength;
    cin >> nLength;
    int nArray[nLength];  // err! can't use variable
    
    return 0;
}

5.2.2 new/delete operator

new operatior can know data type object of object and return pointer as that data type

#include <iostream>
using namespace std;

int main() {
    int *pBuffer; //declare pointer variable to save address
    int nLength;
    
    cout << "memory count allocate heap segment : ";
    cin >> nLength;
    pBuffer = new int[nLength];
    
    for(int i = 0; i < nLength; i++) {
        pBuffer[i] = i + 1;
    }

    for(int i = 0; i<nLength; i++) {
        cout << pBuffer[i] << " ";
    }

    cout << endl;

    delete[] pBuffer;

    return 0;
}

delete operator

delete pBuffer;
delete[] pBuffer;

ref)

profile
프라다 신은 빈지노와 쿠페를 타는 꿈을 꿨다.

0개의 댓글