由于此输出,我的程序停止工作。我该如何解除分配? 我尝试了我的代码,但没有帮助。 完整代码可以在这里找到: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");
}
答案 0 :(得分:2)
假设要通过x
和y
动态分配数组s
,new[]
和n > 1
,您的循环将解除分配x
,第一次y
,s
,然后尝试在下一次迭代中阅读x[i]
。
你应该将delete[]
移到循环之外,或者甚至更好,你应该使用自动清理自己的容器,比如std::vector
:
std::vector<int> x;
std::vector<int> y;
std::vector<int> s;
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;
}
}
答案 1 :(得分:1)
如果您没有使用关键字“new”进行分配,则无需调用delete。如果在堆上分配,则只需要解除分配。使用标准的lib类,让它们在内部对堆执行new / delete。