본문 바로가기

C++

3. new, delete

메모리를 관리하는 문제는 중요한 문제이다. 프로그램이 정확하게 실행되기 위해서는 컴파일 시에 모든 변수의 주소값이 확정되어야만 했다.

하지만 이를위해서는 많은 제약이 따르기 때문에 프로그램 실행 시에 자유롭게 할당하고 해제할 수 있는 힙 이라는 공간이 따로 생겼다.

C 에서는 malloc 과 free 함수를 통해 힙 상에서의 메모리 할당을 지원, C++ 에서도 마찬가지,

언어 차원에서 지원하는 것이 바로 new 와 delete 이다. 

#include <iostream>

int main(){
    int*p = new int;
    *p = 10;

    std::cout << *p << std::endl;

    delete p;

    return 0;
}

int 크기의 공간을 할당하여 그 주소값을 p 에 집어넣었다.

그리고 p 위치에 할당된 공간에 값을 집어넣었고 이를 출력,

마지막으로 할당된 공간을 해제

 

new 로 배열 할당

#include <iostream>

int main(){
    int arr_size;

    std::cin >> arr_size;

    int *list = new int[arr_size];

    for (int i = 0; i < arr_size; i++){
        std::cin >> list[i];
    }

    for (int i = 0; i < arr_size; i++){
        std::cout << list[i] << std::endl;
    }

    delete[] list;

    return 0;
}

먼저 배열의 크기를 잡을 arr_size 라는 변수를 정의, 그 값을 입력 받는다. 

그리고 list 에 new 를 이용하여 크기가 arr_size 인 int 배열을 생성하였다.

 

동물 관리 프로그램

#include <iostream>

typedef struct Animal{
    char name[30];
    int age;

    int health;
    int food;
    int clean;  
} Animal;

void create_animal(Animal *animal){
    std::cin >> animal->name;
    std::cin >> animal->age;

    animal->health = 100;
    animal->food = 100;
    animal->clean = 100;
}

void play(Animal *animal){
    animal->health += 10;
    animal->food -= 20;
    animal->clean += 30;
}

void one_day_pass(Animal *animal){
    animal->health -= 10;
    animal->food -= 30;
    animal->clean -= 20;
}

void show_stat(Animal *animal){

}

int main() {
    Animal *list[10];
    int animal_num = 0;

    for(;;){
        int input;
        std::cin >> input;

        switch(input){
            int play_with;
            case 1:
                list[animal_num] = new Animal;
                create_animal(list[animal_num]);

                animal_num++;
                break;

            case 2:
                std::cin >> play_with;

                if (play_with < animal_num) 
                    play(list[play_with]);

                break;
            
            case 3:
                std::cin >> play_with;
                if (play_with < animal_num) 
                    show_statlist[play_with]);
        }

        for (int i = 0; i != animal_num; i++){
            one_day_pass(list[i]);
        }

    }
    
    for (int i = 0; i != animal_num; i++){
        delete list[i];
    }
}

Animal 구조체를 만들어서 typedef 를 통해 struct Animal 을 Animal 로 간추렸다.

new 로 생성시 create_animal 함수를 통해 각 값들을 초기화,

 

'C++' 카테고리의 다른 글

4.2 함수의 오버로딩, 생성자  (0) 2024.06.29
4. 객체  (0) 2024.06.16
2. 참조  (1) 2024.06.15
1.2 C 와 C++ (기본 문법 비교)  (0) 2024.06.15
왜 C++ 인가 (namespace)  (1) 2024.06.15