Array expansion problems in C ++

I am writing a simulation for a class, and part of it is related to the reproduction of organisms. My organisms are stored in an array and I need to increase the size of the array when I reproduce them. Since I have multiple classes for multiple organisms, I used the 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 pattern seems to mangle my data somehow. I can run the program fine without replaying (by commenting out calls to expandarray), but calling this function causes my program to crash. The program is not reset during the expandarray function, but later crashes on access violation.

I have written functions to expand an array hundreds of times and I have no idea what I screwed up this time. Is there something glaring about my function? Is it right for you?

EDIT: Thanks for helping everyone. I can't believe I missed something so obvious. In response to usage std::vector

: we haven't discussed it in class yet, and oddly enough, I need to write code using the methods we've learned.

+2


source to share


3 answers


You need to transfer oldarray reference: orgType *& oldarray

. The way it is currently written, the function will delete the caller array but not give it the newly allocated one, which will crash.



Better yet, use std::vector

instead of override.

+9


source


The C ++ Standard Library already has functionality written to do this.



Use a container std::vector

.

+3


source


It looks like you are changing the oldarray pointer to point to the new array, but remember in a function that only copies and will not affect the variable you passed. You probably need to pass a pointer reference if you want to do it that way.

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

0


source







All Articles