C++无法删除二维数组的第二维



我正在尝试制作一个指针数组,每个指针都是一个只有1个整数的数组。然后我想打印这个整数,打印完之后,我想删除这个指针,这样它不能再打印了。问题是这个命令";删除[]id_number[i]"似乎不起作用。

The code:

using namespace std;
int main()
{
int** id_number= new int* [12];
for (int i = 0; i < 12; i++)
{
id_number[i] = new int[1];
id_number[i][0] = i;
}
for (int i = 0; i < 12; i++)
{
cout << "id_number ["<< i << "] [0] = "<< id_number[i][0] << endl;
delete[] id_number[i];        //Trying to delete each pointer after printing the 
//integer         
}
cout << endl << "After the end of loop" << endl;
cout << "id_number [" << 5 << "] [0] = " << id_number[5][0] << endl;
return 0;

The outcome:

id_number [0] [0] = 0
id_number [1] [0] = 1
id_number [2] [0] = 2
id_number [3] [0] = 3
id_number [4] [0] = 4
id_number [5] [0] = 5
id_number [6] [0] = 6
id_number [7] [0] = 7
id_number [8] [0] = 8
id_number [9] [0] = 9
id_number [10] [0] = 10
id_number [11] [0] = 11
After the end of loop
id_number [5] [0] = 5     // why does this print work? didn't i delete the pointer "id_number 
// [5]" inside the loop??

用删除条目后

delete[] id_number[i]

将刚才删除的指针设置为类似的nullptr

delete[] id_number[i]; id_number[i] = nullptr;

删除arry中的所有指针后,您仍然拥有占用资源的数组。因此它也必须删除

delete[] id_number; id_number = nullptr;

这将正确释放所有资源。如果你像WhozCraig提到的那样,试图非法访问已删除的资源,就会发生未经授权的行为,我看起来应该这样做,这也是WhozCraigs提到的,只是未经授权行为。

相关内容

  • 没有找到相关文章

最新更新