繁体   English   中英

数组大小调整。 为什么我不能第二次调整数组大小? _CrtIsValidHeapPointer(PUserData)

[英]Array resizing. Why cannot I resize the array second time? _CrtIsValidHeapPointer(PUserData)

我想多次调整数组大小。它第一次这样做,但在那之后,它抛出了一个错误。 当我第二次这样做时,我收到一个错误 _CrtIsValidHeapPointer(PUserData)。 有人可以帮我吗?

int main()
{
    int size = 8;
    int *arr = new int[size];
    arr[1] = 25;
    arr[2] = 30;
    int count = 0;    //to check size
    for (int i = 0; i < size; i++)
    {
        count = count + 1;
    }
    cout << count << endl;
    resize(arr, size);
    int new_count = 0;    //to confirm size change
    for (int i = 0; i < size; i++)
    {
        new_count = new_count + 1;
    }
    cout << new_count << endl;
    resize(arr, size);
    int new_count2 = 0;    //to confirm size change
    for (int i = 0; i < size; i++)
    {
        new_count2 = new_count2 + 1;
    }
    cout << new_count2 << endl;
    return 0;
}
void resize(int *a,int &size)
{
    int newsize = 2 * size;
    int *arr_new = new int[newsize];
    for (int i = 0; i < size; i++)              //copy everything
    {
        arr_new[i] = a[i];
    }
    size = newsize;                 //new value of size
    delete [] a;
    a = arr_new;                    //Pointer pointing to new array
    delete arr_new;
}

这段代码有两个问题:

void resize(int *a,int &size)
{
    [...]

    delete [] a;
    a = arr_new;         //Pointer pointing to new array
    delete arr_new;      // huh????
}

第一个问题是您调用了删除操作符两次; 第一次调用删除旧数组(这是有道理的),但随后您也尝试删除新分配的数组(通过delete arr_new )。 resize()在它返回之前已经删除它时,调用者如何能够使用新分配的数组?

第二个问题是您将a设置为指向新数组(即a = arr_new; ),但a是一个本地函数参数,当resize()返回时超出范围,因此调用代码永远不会看到它的新值. 我认为你想要这个:

void resize(int * & a,int &size)  // note the & before a!

通过引用传递a将允许调用者在resize()返回后看到a的新值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM