如何修复 C++ 中结构的分段错误?
How to fix segmentation fault from structs in c++?
我正在尝试将文本文件中的每个唯一单词写入一个唯一单词结构我还没有那么远,但是在尝试将值写入我的结构数组时出现分段错误。
我们还不能使用指针,因为我们还没有了解它们,我们必须使用 using namespace std。
我很好地弄清楚如何对唯一单词部分使用循环,我只需要帮助弄清楚如何修复分段错误。我已将范围缩小到分段错误从 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;
}
我希望能够将原始文件中的每个单词放入结构数组中。
在结束条件下失去 +1
。
for(int j = 0;j<N/*+1*/;j++){
wordarray[j].word = word1;
}
J 需要从 0 到 N-1。假设 N 为 2,则 wordarray[0] 和 wordarray[1] 有效。 wordarray[2] 不是。
我正在尝试将文本文件中的每个唯一单词写入一个唯一单词结构我还没有那么远,但是在尝试将值写入我的结构数组时出现分段错误。
我们还不能使用指针,因为我们还没有了解它们,我们必须使用 using namespace std。
我很好地弄清楚如何对唯一单词部分使用循环,我只需要帮助弄清楚如何修复分段错误。我已将范围缩小到分段错误从 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;
}
我希望能够将原始文件中的每个单词放入结构数组中。
在结束条件下失去 +1
。
for(int j = 0;j<N/*+1*/;j++){
wordarray[j].word = word1;
}
J 需要从 0 到 N-1。假设 N 为 2,则 wordarray[0] 和 wordarray[1] 有效。 wordarray[2] 不是。