简体   繁体   中英

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.

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.

#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.

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

J needs to go from 0 through N-1. Say N is 2, wordarray[0] and wordarray[1] are valid. wordarray[2] is not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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