views:

111

answers:

3

I'm writing a simulation for class, and part of it involves the reproduction of organisms. My organisms are kept in an array, and I need to increase the size of the array when they reproduce. Because I have multiple classes for multiple organisms, I used a template:

template <class orgType>
void expandarray(orgType* oldarray, int& numitems, int reproductioncount)
{
    orgType *newarray = new orgType[numitems+reproductioncount];

    for (int i=0; i<numitems; i++) {
        newarray[i] = oldarray[i];
    }

    numitems += reproductioncount;

    delete[] oldarray;
    oldarray = newarray;
    newarray = NULL;
}

However, this template seems to be somehow corrupting my data. I can run the program fine without reproduction (commenting out the calls to expandarray), but calling this function causes my program to crash. The program does not crash DURING the expandarray function, but crashes on access violation later on.

I've written functions to expand an array hundreds of times, and I have no idea what I screwed up this time. Is there something blatantly wrong in my function? Does it look right to you?

EDIT: Thanks for everyone's help. I can't believe I missed something so obvious. In response to using std::vector: we haven't discussed it in class yet, and as silly as it seems, I need to write code using the methods we've been taught.

+9  A: 

You need to pass oldarray as a reference: orgType *& oldarray. The way it's currently written, the function will delete the caller's array but will not give it the newly allocated one, causing the crash.

Better yet, use std::vector instead of reimplementing it.

interjay
+3  A: 

The C++ standard library already has functionality written to do this.

Use the std::vector container.

James McNellis
A: 

Looks like you are modifying the pointer oldarray to point to the new array, but remember in the function that's just a copy and won't affect the variable you passed in. You probably need to pass a reference to a pointer if you want to do it this way.

And indeed, std::vector does this for you anyway

John Burton