我想多次调整数组的大小,第一次这样做,但是之后,我抛出一个错误。当我第二次这样做时,我收到错误_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;
}
答案 0 :(得分:1)
此代码有两个问题:
void resize(int *a,int &size)
{
[...]
delete [] a;
a = arr_new; //Pointer pointing to new array
delete arr_new; // huh????
}
第一个问题是您两次调用了delete运算符;第一次调用会删除旧数组(这很有意义),但是随后您也尝试删除新分配的数组(通过delete arr_new
)。 resize()
在返回之前已经删除了新分配的数组,调用者将如何使用它?
第二个问题是您将a
设置为指向新数组(即a = arr_new;
),但是a
是一个局部函数参数,当{{1 }}返回,因此调用代码将永远不会看到其新值。我想您要这样:
resize()
通过引用传递void resize(int * & a,int &size) // note the & before a!
将使调用者可以在a
返回后看到a
的新值。