每次到readTextFile函数中的“g_wordArray [countNumber] = new Word(wordInputTemp)”行时,我都会遇到分段错误。我已经浏览了网站上另一篇描述分段错误原因的帖子,我或者错过了导致它的代码中的内容,或者这不是其中一个原因。另外,在Word类中,我什么都没有,所以它不是那里发生的事情。所有内容都是内联声明的,而且都是空白的。
#include "Word.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
const int FILE_PATH_SZ = 512;
Word **g_wordArray;
int g_arrSz = 50;
Word** allocateArray();
void readTextFile(Word** g_wordArray);
char fileDir[FILE_PATH_SZ], wordInputTemp[256];
int main()
{
g_wordArray = allocateArray();
readTextFile(g_wordArray);
}
Word** allocateArray()
{
Word** g_wordArray = new Word*[g_arrSz];
return g_wordArray;
}
void readTextFile(Word** g_wordArray)
{
ifstream fileInput;
fileInput.open("sample.txt");
int countNumber = 0;
while (fileInput >> wordInputTemp)
{
g_wordArray[countNumber] = new Word(wordInputTemp);
countNumber++;
}
fileInput.close();
return;
}
词类:
class Word
{
public:
Word(const char *word);
~Word();
};
Word构造函数和析构函数:
#include "Word.h"
#include <cstring>
#include <string>
Word::Word(const char *word)
{
len_ = strlen(word) + 1;
ptr_ = new char[len_];
strcpy(ptr_, word);
}
Word::~Word()
{
if (ptr_ != 0)
{
delete [] ptr_;
len_ = 0;
}
}
答案 0 :(得分:0)
您的问题是您永远不会在全局变量中存储值。在分配数组的函数中,您声明一个具有相同名称的局部变量。