누군가이 코드로 문제를 지적 할 수 있습니까 (동적 배열 크기 조정 용). 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. –