简体   繁体   English

如何从C ++中的结构修复分段错误?

[英]How to fix segmentation fault from structs in c++?

I am trying to write each unique word from a text file into a struct of unique words I'm not quite that far yet, but I am getting a segmentation fault when trying to write values into my array of structs. 我正在尝试将文本文件中的每个唯一词写入唯一词结构中,但我还没有那么做,但是在尝试将值写入我的结构数组时遇到了分段错误。

We cannot use pointers as we haven't learned about them yet, and we have to use using namespace std. 我们还不能使用指针,因为还没有了解它们,我们必须使用命名空间std。

I am fine figuring out how to use loops for the unique word portion, I just need help figuring out how to fix the segmentation fault. 我很好地弄清楚了如何对唯一的单词部分使用循环,我只需要帮助弄清楚如何解决分段错误。 I have narrowed it down to where the segmentation fault starts at the for loop in the do-while loop, but I don't know where to go from there and I've found nothing online to help. 我已经将其范围缩小到了do-while循环中for循环中分段错误的起始位置,但是我不知道从那里开始的错误,而且我找不到任何在线帮助。

#include <iostream>
#include <fstream>
#include <cmath>
#include <string>

using namespace std;

struct UniqueWord{
    string word;
    int numOccurences;
};

int main(){

    const int N = 100000;
    ifstream CleanedText;
    CleanedText.open("testTextCleaned.txt"); //change to proper text later
    string word1;
    string words[N];
    for(int i = 0; i < N; i++){
        CleanedText >> words[i];
    }
    CleanedText.close();
    CleanedText.open("testTextCleaned.txt"); //change to proper text later
    UniqueWord wordarray[N];
    for(int i = 0; i < N; i++){
        CleanedText >> word1;
        do{
            for(int j = 0;j<N+1;j++){
                wordarray[j].word = word1;
            }
        }while(words[i] != word1);

    } 

    return 0;
}

I expect to be able to put each word from the original file into the array of structs. 我希望能够将原始文件中的每个单词放入结构数组中。

Lose the +1 on the end condition. 在结束条件上失去+1

        for(int j = 0;j<N/*+1*/;j++){
            wordarray[j].word = word1;
        }

J needs to go from 0 through N-1. J需要从0到N-1。 Say N is 2, wordarray[0] and wordarray[1] are valid. 假设N为2,则wordarray [0]和wordarray [1]有效。 wordarray[2] is not. wordarray [2]不是。

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

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