2017-01-30 110 views
0

有人可以指出这个代码的问题(用于调整动态数组的大小)。我使用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; 
} 
+4

您不使用任何长度信息来创建新的'x'。另请尝试正确格式化代码,以便我们可以更轻松地看到正在发生的事情。 – Matthias247

+6

每当你用C++编程思考“动态数组”时,你的下一个想法总是应该是['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)。使用标准库及其类和函数将使您作为C++程序员*的生活更轻松。 –

+3

这是功课吗?如果不使用std :: vector。 –

回答

3
x = new int[]; 

是作为标准C++无效并且不应当编译。

2

您没有包含具有getchar的库。在开始时添加#include <cstdio>

第二件事是,抓住第一个数字后,你不会增加len,这会导致第二个输入覆盖第一个数字。最后的输入在最后加倍。

三。分配内存时,编译器需要知道需要分配多少内存。您需要在x = new int[]中指定。