我正在學習cpp(我希望我沒有嚇到你已經),我明白指針或引用是什麼,我想我得到什麼對指針的引用是。刪除一個指針引用使程序崩潰
我已經寫了崩潰代碼爲delete[] ranking;
:
open(file)
只是一個簡單的函數打開包含字符串和3點的整數其進入zuzel
結構每行一個txt文件:
void read_file(std::ifstream & file, zuzel *& ranking)
{
if(!open(file))
return; //exit function if reading a file failed
int size = 1;
while(!file.eof())
{
zuzel * update = new zuzel[size];
if(ranking != NULL) memcpy(update, ranking, (size-1)*sizeof(*ranking)); //copy existing contents
file >> update[size - 1].nazwa >> update[size - 1].zawodnicy >> update[size - 1].mecze >> update[size - 1].punkty;// add a new team
delete[] ranking; //delete old data
std::cout << "tst"; //just to see if it crashes
ranking = update;
size++;
}
}
int main()
{
zuzel * rank;
std::ifstream file;
read_file(file, rank);
return 0;
}
我發現,你不應該刪除,你沒有新的東西,但例如代碼不會崩潰:
void funk(int *& a)
{
delete[] a;
}
int main()
{
int a[3] = {3, 4, 6};
int * p = a;
funk(p);
return 0;
}
我該如何解決這個問題?爲了一些簡單的解釋,我很擔心它爲什麼會這樣做。
「不會崩潰」並不意味着代碼是有效的。 – Mat 2014-10-05 11:53:16
'我發現你不應該刪除一些你沒有新的東西,但是例如那個代碼不會崩潰'不能保證像這樣的錯誤的C++代碼會崩潰。 – PaulMcKenzie 2014-10-05 11:59:29
'我正在學習cpp'然後我建議你學會使用'std :: vector'而不是編寫低級C來模擬一個動態數組。 – PaulMcKenzie 2014-10-05 12:01:58