[英]Access Violation Writing to location
我是C ++的新手,我不知道這個錯誤是什么意思。 它從文件讀取,然后嘗試將值存儲在char * []中。
該文件包含:
5,Justin,19,123-45-6789,State Farm,9876,Jessica,Broken Hand,
這是我的代碼。
void Hospital::readRecordsFile(){
std::ifstream fileStream;
fileStream.open(fileName); // Opens the file stream to read fileName
char * temp [8];
int i = 0;
while(!fileStream.eof()){
fileStream.get(temp[i],256,',');
i++;
}
i = 0;
for(char * t:temp){
std::cout << t << std::endl;
}
}
錯誤發生在fileStream.get(temp[i],256,',');
您定義了一個由8個指向char的指針組成的數組,但是忘記分配內存,以便指針指向有效的內存塊:
char * temp [8]; // need then to allocate memory for the pointers
正因為如此,
fileStream.get(temp[i],256,',')
您最終會使用不是您的內存。
解:
for(int i = 0; i<8; i++)
temp[i] = new char[256]; // we allocate 256 bytes for each pointer
不過,最好使用std::vector<std::string>
代替。
在您現在擁有的代碼中,您似乎隱式地假設該文件的行數不超過8行,我很難相信。 如果您的文件有8行以上,那么您最終將無法訪問8個指針的數組,因此您將獲得另一個未定義的行為(通常是段錯誤)。 這就是為什么最好使用標准的STL容器(如std::vector
)來避免所有這些麻煩的事情。
如果您必須使用指針並且想要可變數量的行,那么您必須使用指向指針的指針,
char** temp;
然后為足夠的指針分配給字符的內存,
temp = new char* [1000]; // we believe we won't have more than 1000 lines
然后,為每個指向字符的指針分配內存
for(int i = 0; i < 1000; ++i)
temp[i] = new char[256];
在程序末尾,您必須按照相反的順序delete[]
for(int i = 0; i < 1000; ++i)
delete[] temp[i];
delete[] temp;
如您所見,它變得凌亂。
您從未為temp
每個指針分配內存。
您可能想要類似的東西:
for (unsigned int i = 0u; i < 8; ++i)
{
temp[i] = new char[256];
}
The說temp
變量指向8個動態分配的字節緩沖區,每個256個字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.