Expanding a dynamic array by passing it inside a function

66 Views Asked by At

i have an array with an initial size

int size = 5; //initial size ofwordsArray
wfpPointer wordsArray = new WordFrequencyPair[size];

where wfpPointer is a typedef for a pointer that points to the adress of a variable of type WordFrequencyPair.

now when i detect that my array is full i call the following function to expand it:

int expandWordsArray(WordFrequencyPair wordsArrayIn[], int currentSize){

    int newSize = currentSize * 2;
    wfpPointer newArray = new WordFrequencyPair[newSize];

    for(int i = 0; i < currentSize; i++)
        newArray[i] = wordsArrayIn[i];

    delete [] wordsArrayIn;
    wordsArrayIn = newArray;



    return newSize;



}

the thing is when i write this code in the main without calling the function it works perfectly fine and the array expands. From within the function however my program crashes. Note: eclipse gives me no errors and compiles the program without trouble.

Plz help

Thank you

1

There are 1 best solutions below

2
On

You are passing the array (that is, a pointer to the first element of the array) by value. The function deletes, the array (using the original value of the pointer), then constructs a new array on the heap and points the local pointer to it.

Meanwhile, back in the calling code (main), the pointer hasn't changed and the old array has been deleted. When you try to dereference the pointer, BOOM!

You should pass the pointer by reference:

int expandWordsArray(WordFrequencyPair *&wordsArrayIn, int currentSize)