2016-01-23 36 views
-1

每次在readTextFile函數中到達「g_wordArray [countNumber] = new Word(wordInputTemp)」行時,都會出現分段錯誤。我已經瀏覽了網站上的另一篇文章,描述了分段錯誤的原因,而且我錯過了導致它出現在代碼中的內容,或者這不是其中的原因。另外,在課堂上,我沒有任何東西,所以它不是在那裏發生的事情。一切都是內聯聲明的,全都是空白的。分段錯誤問題C++

#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(); 
}; 

字構造函數和析構函數:

#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

「Word」的定義是什麼? – Dai

+1

[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve) – Drop

+0

爲什麼使用全局變量? –

回答

0

你的問題是,你永遠不會存儲在全局變量的值。在分配數組的函數中,聲明一個具有相同名稱的局部變量。