c – 删除使用new创建的2D或3D指针
作者:互联网
如何删除使用new创建的2D或3D指针?我知道删除[] name_of_pointer可以删除1D指针.
// 1D pointer:
int *pt1 = new int[size]; // Creating 1D pointer
delete [] pt1; // Deleting 1D pointer
// 3D pointer L: # of layers, R: # of rows, C: # of columns
int (*pt2)[L][R][C] = new int[1][L][R][C]; // L:2, R:2, C:3 (ex. below)
delete [] pt2;
我使用它来创建和删除3D指针,但它只删除了指针pt2的前两个条目,无论我运行代码多少次,其余10个条目保持不变.
例如:
int B[2][2][3] = {{{0,1,2},{3,4,5}},{{6,7,8},{9,10,11}}};
int (*pb)[2][2][3] = new int[1][2][2][3];
for(int k=0; k<2; k++){
for(int j=0; j<2; j++){
for(int i=0; i<3; i++){
*(*(*(*(pb)+k)+j)+i) = B[k][j][i];
cout << "k,j,i: " << k << "," << j << "," << i;
cout << " " << B[k][j][i] << " " << *(*(*(*(pb)+k)+j)+i) << endl;
};
cout << endl;
};
cout << endl;
};
delete [] pb;
for(int k=0; k<2; k++){
for(int j=0; j<2; j++){
for(int i=0; i<3; i++){
cout << "k,j,i: " << k << "," << j << "," << i;
cout << " " << B[k][j][i] << " " << *(*(*(*(pb)+k)+j)+i) << endl;
};
cout << endl;
};
cout << endl;
};
我得到了(k,j,i)=(0,0,0)&的垃圾值. (0,0,1)对pb执行删除操作后,其余所有10个值保持不变.
解决方法:
您的代码正在检查已删除数组的值.这是未定义的行为.无法安全地检查这些元素现在具有的值,因为它们不再存在.
此外,删除[]不需要将其删除的对象“清零”.您不能假设因为未修改内存,所以不会删除对象.
标签:c,pointers,new-operator,delete-operator 来源: https://codeday.me/bug/20190731/1586599.html