分段错误当我试图运行程序时出错

Segmentation Fault Error when I try to run program

本文关键字:运行 程序 出错 错误 分段      更新时间:2023-10-16

我一直收到一个分段错误。我试图让用户键入整数,并返回向量中和的索引。请帮助

#include <iostream>
#include <vector>
#include <string>
using namespace std;
void print (const vector<int> *result) {
cout << "[";
for (int i {0};i<(*result).size();++i) {
cout << (*result).at(i) + " ";
}
cout << "]" << endl;
}
vector<int> *method(const vector<int> *vec,int value) {
vector<int> *newvec {nullptr};
bool done {false};
int i = (*vec).size()-1;
while (!done && i >= 0) {
if (value >= (*vec).at(i)) {
value -= (*vec).at(i);
(*newvec).push_back(i);
} 
if (value == 0) {
cout << "done" << endl;
done = true;
} else {
--i;
}
}
return newvec;
}
int main()
{
vector<int> v;
int Numbers;
cout << "Enter a list of numbers (put spaces inbetween): ";
while (cin >> Numbers && Numbers != -1) {
v.push_back(Numbers);
}
cout << endl;
int number {};
cout << "Enter a number: ";
cin >> number;
cout << endl;
vector<int> *results = method(&v,number);
print(results);
//del results;
return 0;
}

我不太确定为什么,但分割错误不断出现。这是我不理解的逻辑吗?我相信它涉及指针,但不太确定。

vector*newvec从未被创建为向量,因此它只是一个指向向量的指针,然后用于插入值。

在这种情况下最好不要使用指针,而是返回/使用对对象的引用。

即:

vector<int> method(const vector<int> &vec,int value) {
vector<int> newvec;
bool done {false};
int i = vec.size()-1;
while (!done && i >= 0) {
if (value >= vec.at(i)) {
value -= vec.at(i);
newvec.push_back(i);
} 
if (value == 0) {
cout << "done" << endl;
done = true;
} else {
--i;
}
}
return newvec;
}

并在main中对其他函数调用执行类似操作。

vector<int> *newvec {nullptr};

在这里,您可以创建一个空指针。

然后尝试取消对它的引用,并使用它所指向的向量,但该向量并不存在。

你必须实际创建一个向量。

总的来说,我建议去掉所有这些指针;您不需要它们,而且您已经发现它们使您的代码变得更加复杂和容易出错。

只需以通常的方式创建漂亮的法线向量。