由於此輸出,我的程序停止工作。我怎樣才能釋放它? 我試過我在我的代碼中,但沒有幫助。 完整的代碼可以在這裏找到:full code如何取消分配數組內存?
for (i = 0 ; i < n ; i++) {
if (
!((x[i] >= 0) && (x[i] <= a) &
(y[i] >= 0) && (y[i] <= b)
)
) {
cout << x[i] << ' ' << y[i] << ' ' << s[i] << ' ' << "SPADOL" << endl;
} else {
cout << x[i] << ' ' << y[i] << ' ' << s[i] << endl;
} // ALLOCATION IS DONE AT THIS POINT
delete [] x;
delete [] y;
delete [] s;
}
當我運行這段代碼,我開始輸入x和y,並在之後我鍵入y值,程序停止工作。當我只輸入一行時,程序執行完美,但是當我想要輸入多行時出現問題,..在第一個輸出打印出來後,程序崩潰。 我的全代碼載體:
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <string>
using namespace std;
// vector<string> inputs;
int n; // pocet uloh
int a; // rozmer obdlznika a
int b; // rozmer obdlznika b
vector<int> x;
vector<int> y;
vector<string> s;
int i;
int d;
static const char alpha[] = {'D', 'L', 'P'};
char genRandom()
{
return alpha[rand() % strlen(alpha)];
}
// end of generator
int main() {
cin >> n;
while(!((n >= 1)&&(n <=15000)))
{
cout << "max 15000" << flush;
cin >> n;
}
cin >> a >> b;
while(!((a >= 1)&&(a <=100) & (b >= 1)&&(b <= 100)&&(a!=b)))
{
cout << "chyba max 100 alebo a!=b" << endl;
cin >> a >> b;
}
for (i = 0; i < n; i++)
{
cout << "Uloha " << i+1 << ":" << endl;
cin >> x[i];
cin >> y[i];
cin >> s[i];
while(!((x[i]>=0)&&(x[i]<=a))) {
cout << "Try Again x: " << flush;
cin >> x[i];}
while(!((y[i]>=0)&&(y[i]<=b))) {
cout << "Try Again y: " << flush;
cin >> y[i];}
if (s[i] == "S"){
y[i] = (y[i]+1);
}else if (s[i] == "J"){
y[i] = (y[i]-1);
}else if (s[i] == "V"){
x[i] = (x[i]+1);
}else if (s[i] == "Z"){
x[i] = (x[i]-1);
}
cin >> d;
while(!((d>=1)&& (d<=200))) {
cout << "Try Again d: " << flush;
cin >> d;}
for (int counter=0; counter<d; counter++)
{
cout << genRandom();
}
cout << endl;
} // koniec for
for (i = 0 ; i < n ; i++)
{
if(!(((x[i]>=0)&&(x[i]<=a)) | ((y[i]>=0)&&(y[i]<=b)))){
cout << x[i] << ' ' << y[i] << ' ' << s[i] << ' ' << "SPADOL" << endl;
}else{
cout << x[i] << ' ' << y[i] << ' ' << s[i] << endl;
}
}
system("pause");
}
您不顯示完整的代碼...分配完成在哪裏? –
當提供代碼以顯示問題時,請包括產生錯誤所需的所有代碼,並刪除與該錯誤無關的代碼。例如,你提供的大部分代碼(整個'if' /'else'塊)對分配和釋放都不起作用,所以對於這個問題來說是純粹的噪音。作爲獎勵,如果你在發佈你的問題之前這樣做了,你可能會看到你在循環內部刪除了[]數組,因此你可以在發佈之前找出錯誤。 – mah
鏈接的代碼使用'malloc'。在這種情況下,您需要使用'free'釋放,而不是'delete'。 – Mat