虽然你已经写了将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