Question

So this is my function.

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,size,type,compareValue};
}

Here's where I initialise my struct

StoredData testData[5]={{0,50,5,1},{1,25,5,2},{2,40,2,3},{3,10,5,4},{4,80,3,5}};

Now, I'm about 20% sure that the reason why it isn't working is because I need to use the NEW function to create the data, but I've trying searching the web and I can't find anything to help me.

What I want to happen, is I want to pass the struct array through the function to increase its size by 1.

Was it helpful?

Solution

There are a few problems here. One of them is as you suspect, you cannot delete something that was statically defined. That problem can be got past by having a static definition and an initialization function that performs the dynamic allocation and copies the static data in.

Another issue is that you're using call-by-value on the temp variable. This might be less than obvious since, as you know, you're able to modify the data temp points to -- the problem is that you also want to perform temp = tempStruct; where, presumably, you want to affect the caller's view of the value passed in... if you want to affect what the caller sees, you need to call-by-reference.

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