代碼來自我的朋友。請看看它,並給我們一些建議。C++不知道內容改變的原因
in VoltageForDisplayAndAnalyze.h file
private:
string * grpVolFileName[ MAX_NUM_OF_GROUP ]; //for voltage files
fstream * aStream_grpVolt[ MAX_NUM_OF_GROUP ];
in VoltageForDisplayAndAnalyze.CPP file
void VoltageForDisplayAndAnalyze::MakeFileNameForGroupCell(int xgrpIndex)
{
int numOfFiles = (EEnd - EBegin + 1)/255;
grpVolFileName[ xgrpIndex ] = new string[ numOfFiles ];
assert(grpVolFileName[ xgrpIndex ] != NULL);
aStream_grpVolt[xgrpIndex] = new fstream[ numOfFiles ];
assert(aStream_grpVolt[ xgrpIndex ] != NULL);
.....
for(int fileIndex=0; fileIndex<numOfFiles; fileIndex++)
{
char * tempbuf = new char[256];
memcpy(tempbuf, mPath.c_str(), mPath.length());
tempbuf[mPath.length()] = '\0';
char * numChar = new char[4];
itoa(xgrpIndex, numChar, 3);
numChar[3] = '\0';
strcat(tempbuf, numChar);
grpVolFileName[ xgrpIndex ][ fileIndex ].assign(tempbuf);
}
....
}
我們在上面的方法中打印出來,給grpVolFileName賦值,結果看起來不錯。這些值是某些文件的位置。然後調用以下方法來使用上面的字符串指針的grpVolFileName數組。這對第一個4是好的,然後打印出來顯示目錄不能正確打印出來,有些正方形打印出來,併發生錯誤。但它並不總是在第四次,有時它剛剛開始。
void VoltageForDisplayAndAnalyze::SaveDataForGrpCell(int grpIndex, int fileIndex, int xBegin, int xEnd {
int i = 0;
char answer;
//save to hard disk
aStream_grpVolt[grpIndex][fileIndex].open( grpVolFileName[grpIndex][fileIndex].c_str() , fstream::out | std::ofstream::app);
cout << "open file: grpIndex= " << grpIndex <<" fileIndex= " << fileIndex << " : " << grpVolFileName[grpIndex][fileIndex] << " to save." << endl;
if(aStream_grpVolt[grpIndex][fileIndex].good())
{
//.....
}
else
{
cout << "Cannot open file: " << grpVolFileName[grpIndex][fileIndex] << endl;
}
//.......
}
打印出從上方象那些方法:
...
open file: grpIndex= 2 fileIndex= 0 : C:\Workspace\UncusJava\DataFiles\spc1\2 to save.
open file: grpIndex= 3 fileIndex= 0 : C:\Workspace\UncusJava\DataFiles[][][][][email protected] to save.
這意味着grpVolFileName陣列已經在過程被改變。如果條款if(aStream_grpVolt[grpIndex][fileIndex].good())
導致此錯誤,則返回錯誤併發生錯誤。
我搜索了整個解決方案(Visual Studio 2008),上面兩個方法都是隻使用grpVolFileName指針數組的地方。這是這部分的單線程。
有何評論?
真是一團糟。這使我的眼睛流血。我不得不把他們趕走。 – sbi 2010-02-17 18:14:04
這不是對你的問題本身的答案,而是使用std :: vector而不是數組,而std :: string而不是字符數組會極大地簡化你的代碼。 – luke 2010-02-17 18:14:27
友好的建議:我們在這裏是因爲我們想要幫助你,但老實說,你發佈的代碼乍一看有點嚇人。我會考慮簡化它,只有真正重要的是我們。改變標識符名稱,以便我們立即瞭解他們的存在理由;重新編寫你的問題文本,以便簡明扼要;並確保你清楚地陳述你想要達到的目標。儘可能少地使用單詞來獲得我們需要知道的所有內容:通過這種方式,我們將通過更高的機會閱讀您的問題。 – wilhelmtell 2010-02-17 19:19:26