Question

The purpose of this function is to take a struct, and enlarge the array by 1. It does this by copying the array to a temporary array, deleting and recreating the original with a larger size. My problem is that when I run the function, all of my values within the struct become '-17891602'. Correct me if I'm wrong, but I believe that this is the value that shows when the variable has been deleted? I can't figure out the problem. But here's the definition.

void Array::addValueStruct(int id, int size, int type, int compareValue, StoredData temp[])
{
    //struct
    StoredData* tempStruct = new StoredData [arrSize+1];
    for (int i=0;i<arrSize;i++)
    {
        tempStruct[i] = temp[i];
    }

    arrSize = arrSize + 1;

    delete [] temp;

    temp = tempStruct;

    temp[arrSize-1].id = id;
    temp[arrSize-1].size = size;
    temp[arrSize-1].type = type;
    temp[arrSize-1].compareValue = compareValue;
}

Also, not sure if this is helpful, but the function call.

test.addValueStruct(5,5,5,5,testData);

UPDATE: Problem solved!

Was it helpful?

Solution

The issue is that the array pointer is passed into the function by value. This means that when you reassign it to point to a different array, this change does not propagate back to the caller.

You need to pass it either by pointer or by reference.

OTHER TIPS

You are passing temp by value. Therefore, addValueStruct gets its own copy and changes made to it are not visible outside that function scope.

The problem probably is this line here:

temp = tempStruct;

Here you only changing the local copy of the temp variable. If you want to modify the variable used for the call you have to pass it by reference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top