user1721803
user1721803

Reputation: 1195

Visual Studio pointer error

When I run this code:

#include <iostream>

using namespace std;

void makeArrayBigger(int*, int&, int);
void arrayIni(int*, int, int);
void displayArray(int*, int);

int main(){

    int size = 5;
    int *arr = new int[5];

    arrayIni(arr, size, 0);
    //displayArray(arr, size);


    makeArrayBigger(arr, size, 8);
    //displayArray(arr, size);


    arrayIni(arr, size, 1);

    system("pause");
    return 0;

}

void makeArrayBigger(int *arr, int &size, int newSize){
    int *newArr = new int[newSize];

    for (int counter = 0; counter < size; counter++){
        newArr[counter] = arr[counter];
    }

    delete[] arr;
    arr = new int[newSize];
    for (int index = 0; index < size; index++){
        arr[index] = newArr[index];
    }
    delete[] newArr;
    size = newSize;
}

void arrayIni(int *arr, int size, int ini){

    for (int index = 0; index < size; index++){
        arr[index] = ini;
    }
}

void displayArray(int *arr, int size){

    if(arr == NULL)
        return;
    for (int counter = 0; counter < size; counter++){
        cout << arr[counter] << endl;
    }

    cout << endl;
}

I get this breakpoint error:

Windows has triggered a breakpoint in pointer.exe.

This may be due to a corruption of the heap, which indicates a bug in pointer.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while pointer.exe has focus.

Upvotes: 0

Views: 823

Answers (2)

Steve
Steve

Reputation: 1510

The reason of this error is that you confused the conception 'Pass by value' with 'Pass by Reference'. The answer of the following question might be an good reference:

What's the difference between passing by reference vs. passing by value?

The problem will be fixed by replacing the void makeArrayBigger() interface with the following codes

void makeArrayBigger(int* &arr, int &size, int newSize);

Update:

when I pass a pointer I'm passing a pointer that points to that same location.

It is the same location but not the same pointer. Whether delete or malloc the new pointer will not change the value of the actual parameter.

In this case, the arr pointer keeps the same size after makeArrayBigger(). But it will be assumed to be the new size(8) in arrInit().

Upvotes: 1

Chris
Chris

Reputation: 2763

Pass in a reference to the array (int*) just like you pass a reference to the array size (int). Then you can replace the array with a new array and update the size as you are currently doing:

void resize (int*& array, int& arraySize, int newSize)
{
    delete [] array;

    arraySize = newSize;
    array = new int [arraySize];
}

int main() {

    int testSize = 5;
    int* testArray = new int [testSize];

    // Do stuff

    resize (testArray, testSize, 8);

    // Do more stuff

    delete [] testArray;

    testArray = NULL;
    testSize = 0;

    return 0;
}

Upvotes: 1

Related Questions