Mar*_*Rob 3 c++ arrays heap memory-management dynamic-arrays
所以,我有这个代码,我试图ppint在最后解除分配数组.我曾尝试使用Xcode泄漏来确定它是否正常工作,但我不太明白.会这样做吗?
delete ppint[0];
delete ppint[1];
delete ppint[2];
delete ppint[3];
Run Code Online (Sandbox Code Playgroud)
或者还有其他必须做的事吗?
#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
int main()
{
int **ppint;
ppint = new int * [4];
for(int i = 0; i < 4; i++ ) {
ppint [i] = new int[4];
} // declares second layer of arrays
for(int i = 0, count = 0; i < 4; i++ ) {
for(int j = 0; j < 4; j++ ) {
count++;
ppint [i] [j] = count;
} //init part 2
} // init array
for(int i = 0; i < 4; i++ ) {
for(int j = 0; j < 4; j++ ) {
cout << ppint [i] [j] << endl;
} // print part 2
} //print array
}
Run Code Online (Sandbox Code Playgroud)
关.你必须使用,delete[]因为你分配了每个new[]:
delete[] ppint[0];
delete[] ppint[1];
delete[] ppint[2];
delete[] ppint[3];
Run Code Online (Sandbox Code Playgroud)
但是当然,你应该使用一个循环:
for(int i = 0; i < 4; i++ ) {
delete[] ppint[i];
}
Run Code Online (Sandbox Code Playgroud)
然后不要忘记delete[] ppint自己:
delete[] ppint;
Run Code Online (Sandbox Code Playgroud)
但是,在C++中,我们宁愿不搞乱动态分配的数组.使用a std::vector<std::vector<int>>或a std::array<std::array<int, 4>, 4>.如果您关心数据的位置,请尝试boost::multi_array.