繁体   English   中英

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

[英]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 永远不会被创建为向量,所以它只是一个指向向量的指针,然后你可以用它来插入值。

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

IE:

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};

在这里,您实际上创建了一个空指针。

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

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

一般来说,我会建议摆脱所有这些指针; 您不需要它们,并且您已经发现它们使您的代码更加复杂和容易出错。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM