lundi 30 janvier 2017

Declaring Dynamic array in a function

I am making a function that re-allocate a new dynamic array if the previous array is full. However, If I compile it, a run-time error happens. When I debug it with Visual Studio 2015, it seems that, after function is done, the compiler cannot access to the dynamic array or the array is deleted. Can you tell me why?

void reallocateMemory(string* arr, int& physicalSize, int addedMemory) {
    string* result = new string[physicalSize + addedMemory];
    for (int i = 0; i < physicalSize; i++) {
        result[i] = arr[i];
    }

    delete[] arr;

    arr = result; // After this code, it seems variable arr works well.
    result = nullptr;
    physicalSize += addedMemory;
} // However, when the function returns, arr cannot access a dynamic array.

Aucun commentaire:

Enregistrer un commentaire