【发布时间】:2012-02-27 02:39:41
【问题描述】:
我正在为我的 GUI 编程课做一个作业,我们将在其中制作一个 Windows 程序,以十六进制显示文件的内容。我有一个包含文本并以字符串格式创建十六进制的类。
我正在尝试创建一个字符数组来存储每一行以供输出。但是,当我使用 new 创建字符指针数组时,出现访问冲突错误。
我进行了一些搜索,但没有找到答案。
该类有这些成员变量:
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。这不是我在编译器中的首选,但它是我们老师希望我们使用的。
【问题讨论】:
标签: c++ access-violation new-operator