0
我正在爲我的GUI編程類做一個任務,在其中我們要創建一個以十六進制顯示文件內容的Windows程序。我有一個保存文本並以字符串格式創建十六進制的類。使用新命令訪問衝突錯誤
我試圖創建一個字符數組的數組來存儲每行輸出。但是,當我使用新的來創建字符指針數組時,出現訪問衝突錯誤。
我已經做了一些搜索,但沒有找到答案的運氣。
的類有這些成員變量:
char* fileText;
char** Lines;
int numChars;
int numLines;
bool fileCopied;
我的構造函數:
Text::Text(char* fileName){ //load and copy file.
fileText = NULL;
Lines = NULL;
fileCopied = ExtractText(fileName);
if (fileCopied) {
CreateHex();
}//endif
}//end constructor
ExtractText加載給構造函數中的文件,並將其複製成一個大的字符串。
bool Text::ExtractText(char fileName[]){
char buffer = '/0'; //buffer for text transfer
numChars = 0; //initialize numLines
ifstream fin(fileName, ios::in|ios::out); //load file stream
if (!fin) { //return false if the file fails to load
return false;
}//endif
while (!fin.eof()) { //count the lines in the file
fin.get(buffer);
numChars++;
}//endwh
fileText = new char[numLines]; //create an array of strings, one for each line in the file.
fin.clear(); //clear the eof flag
fin.seekg(0, ios::beg); //move the get pointer back to the start of the file.
for (int i = 0; i < numChars; i++) { //copy the text from the file into the string array.
fin.get(fileText[i]);
}//endfr
fileText[numChars-1] = '\0';
fin.close();
numLines = (numChars % 16 == 0) ? (numChars/16) : (numChars/16 + 1);
return true;
}//end fun ExtractText
然後出現問題代碼。在CreateHex函數中,第一行是嘗試創建字符指針數組的地方。
void Text::CreateHex(){
Lines = new char*[numLines];
只要程序運行那行代碼,那就是當我得到訪問衝突時。我不確定問題是什麼,因爲我在之前的程序中使用過完全相同的方法。唯一的區別是指針的名字。如果這有什麼不同,我使用Borland C++ 5.02。這不是我在編譯器中的第一選擇,但它是我們的老師希望我們使用的。
NumLines在ExtractText的末尾設置爲文件中16個字符行的數量。 – tokomonster 2012-02-26 20:40:45
確實,但是它已經被使用了! – 2012-02-26 22:19:16
CreateHex僅在ExtractText完成後運行。 numLines在ExtractText結尾處設置爲正值,非零值。看看構造函數。運行ExtractText,如果它返回true,則運行CreateHex。如果ExtractText返回true,那麼numLines的值必須至少爲1,除非可能是我嘗試加載空白文件,但這不是我所遇到的問題。我可以向你保證,並且我已經通過調試來驗證它,numLines在使用時具有正的非零值。 – tokomonster 2012-02-26 23:17:06