雖然你已經寫了將tempRow設置爲NULL,它不會釋放你分配的內存。爲此你需要
free(tempRow);
tempRow = NULL;
但是如果你使用C++作爲標籤建議,你會更好使用C++新/刪除
double* tempRow;
tempRow = new double[size];
...
delete [] tempRow;
tempRow = NULL;
,你甚至可以使用STL處理您爲你分配內存。
std::vector<double> tempRow(size);
// You can access the data, in a similar way to an array
tempRow[5] = tempRow[4]+tempRow[3];
// If you really need to access the underlying pointer, (To pass to another
// function for example) you can do this. Note that the pointer will be valid
// until the vector is destroyed or modified in certain ways that can cause the
// vector to reallocate its memory. So you can't use this to pass data to a
// function that destroys or takes ownership of the passed in pointer.
fn_requiring_pointer(&temp[0]);
// The memory used in tempRow will get cleaned up automatically when the
// object goes out of scope
//
// If I really need to free up the memory used in it early I can use a swap
// hack. (iirc tempRow.clear() isn't guaranteed to release the memory)
std::vector<double>().swap(tempRow); // Unneeded in most cases.
也試圖重用tempRow指針的東西不相關可能沒有必要。只需創建一個不同名稱的新指針。重複使用變量形式多個不同的不相關的目的可能會使代碼很難在以後明白。
那麼,你從學習這本書嗎?這是非常糟糕的C++代碼,很簡單,並且被任何[入門書]所覆蓋(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。您應該選擇一個,以便您可以學習C++。答案當然是使用'std :: vector'。 「看起來不起作用」爲 –
GManNickG
2010-10-19 06:14:13
-1。 – 2010-10-19 07:31:24
似乎不起作用的是指代碼上面的句子。即使用提供的代碼「在初始化指針並指向一行後取消設置指針......似乎不起作用。」 – Stuart 2010-10-19 16:04:53