리메이크 중/C,C++ 실습 중심

C&C++ a1 동적할당 연습

라이피 (Lypi) 2023. 2. 14. 23:19
반응형

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    char name0[100];
    int nameVolume = 1;
    char** nameList = new char*[nameVolume];
    int count = 0;

    while(true) {
        cout << "너의 이름에는 힘이 있다. 이름을 입력하라." << endl;
        cin >> name0;
        

        if(strcmp(name0, "EXIT") == 0) {
            return 0;
        }

        nameList[count] = new char[strlen(name0)+1];
        strcpy(nameList[count],name0);

        cout << "현재 저장된 이름의 갯수" << endl << count+1 << endl;
        cout << "현재 저장된 이름 목록" << endl;

        for (int i = 0; i <= count; i++) {
            cout << nameList[i] << endl;
        }

        if(count+1 >= nameVolume) {
            nameVolume++;
            char* tempList[nameVolume];
            memcpy(&tempList, &nameList, sizeof(nameList));
            nameList = new char*[nameVolume];
            memcpy(&nameList, &tempList, sizeof(tempList));

        }
        cout << "끝내려면 EXIT" << endl;
        count++;
    }

    for (int i = 0; i < count; i++) {
        delete nameList[i];
    }
    delete[] nameList;

    return 0;
}

◆  버퍼에 문자열을 입력받고 이름의 길이만큼 문자열 배열을 동적할당 받는다.

◆  이를 저장하기 위한 리스트를 1개씩 동적할당한다.

◆  1개씩 하면 매번 새로운 이름을 입력할 때 마다 동적할당을 반복해야해서 퍼포먼스가 떨어지지만

◆  이번에는 연습이니까 확인을 쉽게 하기 위해서 매번 해주도록 했다.

◆  5개씩 하려고 하니까 세그멘테이션 오류가 떳다... 

◆  사실 C++을 쓰면 string과 Vector를 쓰면 해결될 문제. 

◆  물론 string과 Vector를 공부해야함...

반응형