有人可以指出这个代码的问题(用于调整动态数组的大小)。我使用Visual Studio 2013来运行代码。它给出了运行时错误,即heap corruption detected after normal block (a number) at (memory address). CRT detected that the application wrote to the memory after the end of heap buffer
。 我使用以下提及的技术,而不是任何标准库函数或向量用于调整阵列:调整动态数组的大小
#include<iostream>
using namespace std;
int * rg(int *, int, int);
int main()
{
int len = 1;
int * x = new int[len];
int i = 0;
int y = 0;
while (getchar() != 'q')
{
cin >> y;
if (i == 0)
x[0] = y;
else
{
x = rg(x, len, y);
len++;
}
cout << len;
i++;
}
cout << endl;
for (int i = 0; i < len; i++)
{
cout << x[i] << endl;
}
}
int * rg(int*x, int len, int val)
{
int * temp = x;
x = new int[];
for (int i = 0; i < len; i++)
{
x[i] = temp[i];
}
x[len] = val;
delete[]temp;
return x;
}
您不使用任何长度信息来创建新的'x'。另请尝试正确格式化代码,以便我们可以更轻松地看到正在发生的事情。 – Matthias247
每当你用C++编程思考“动态数组”时,你的下一个想法总是应该是['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)。使用标准库及其类和函数将使您作为C++程序员*的生活更轻松。 –
这是功课吗?如果不使用std :: vector。 –