问题展开C中的数组++ [英] Problems Expanding an Array in C++

查看:148
本文介绍了问题展开C中的数组++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一类模拟和它的一部分涉及到生物的繁殖。我的有机体都保存在一个数组,我需要增加数组的大小时,他们重现。因为我有多个类多种生物,我用一个模板:

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;
}

不过,这个模板似乎在某种程度上破坏我的数据。我可以毫不再现(注释掉调用expandarray)运行程序很好,但调用这个函数会导致我的程序崩溃。该方案不崩溃期间expandarray功能,但后来在访问冲突崩溃。

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?

编辑:感谢大家的帮助。我无法相信我错过了什么那么明显。为了应对使用的std ::矢量:我们还没有在课堂上讨论它,并且愚蠢的,因为它似乎,我需要使用方法写入code我们一直被教导。

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.

推荐答案

您需要通过oldarray作为参考: orgType *放大器; oldarray 。它是目前编写方式,功能会删除来电者的阵列,但不会给它新分配的,导致崩溃。

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.

更重要的是,使用的std ::矢量,而不是重新实现它。

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

这篇关于问题展开C中的数组++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆