分段错误当我试图运行程序时出错
Segmentation Fault Error when I try to run program
我一直收到一个分段错误。我试图让用户键入整数,并返回向量中和的索引。请帮助
#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};
在这里,您可以创建一个空指针。
然后尝试取消对它的引用,并使用它所指向的向量,但该向量并不存在。
你必须实际创建一个向量。
总的来说,我建议去掉所有这些指针;您不需要它们,而且您已经发现它们使您的代码变得更加复杂和容易出错。
只需以通常的方式创建漂亮的法线向量。
相关文章:
- 运行程序时出现问题
- 分段错误当我试图运行程序时出错
- C++ 每次运行程序时我都会"nan"输出的问题
- 通过 g++ 运行程序时没有这样的文件或目录
- 重新运行程序和字符串流?
- 无法在 VS Code 上使用代码运行程序运行C++文件
- 使用有限的 RAM 运行 c++ 程序
- 继续运行程序而无需任何干预,直到要求退出为止
- 如何在每次运行程序时写入文件的下一行?
- 控制台在运行C ++程序后立即关闭(无需调试)
- 运行程序时找不到共享对象库,但在编译过程中链接了它
- 远程运行程序
- 在 Heroku 上运行 C++ 程序
- 如何在Powershell中运行C++程序,就像CMD一样?
- 为什么与Java和Python相比,使用Cmake运行C++程序每次都需要这么长时间?
- C++随机数生成器通常在 Visual Studio 中运行程序时在 2 次后停止生成数字
- 崇高文本 3 - 在终端中编译并运行 C++ 程序(路径包含空格)
- 我收到阻止我运行程序的警告,但不确定如何解决
- C++ Visual Studio 无法完全运行程序
- 在SIGABRT c ++信号之后继续运行程序