c++ - 在 C++ 中,使用指针多维和Multipointer删除数组

  显示原文与译文双语对照的内容
0 0

所以我知道多个维数/数组会混淆,但是如何正确地对这些类型的数组进行? 我知道语法,但是添加多个维度/指针会变得。 下面是一些代码段代码:


//FIRST PROBLEM
//function to add an item to a pointer array
//due to problems in adding something directly, I created a temp
//temp is not necessary if there's a way without it
 int y = 6;
 int x = 5;
 int *myList = new int[x];
 void List::add(int newInt)
 {
 void List::add(int newInt){
 int *temp = new int[x+1];
 temp = myList;
 temp[x+1] = newInt;
 delete [] myList;
 int *myList = temp;
 }

//SECOND PROBLEM----tricky multidimensional
//not getting any errors, but not sure if done properly
 int x;
 int y;
 int** myMatrix;
 cout <<"How many rows?" <<endl;
 cin>> x;
 myMatrix = new int*[x];
 cout <<"How many columns?" <<endl;
 cin>> y;
 for (int i=0; i<x; i++)
 myMatrix[i] = new int[y];
 for(int i=0; i<10; ++i){
 for(int j=0; j<10; ++j){
 myMatrix[i][j] = rand();
 } 
 for(int i = 0 ; i <x ; ++i)
 {
 for(int j = 0 ; j <col ; ++j){
//delete[] myMatrix[i][j]; (tried this method, did not work)
 }
 delete[] myMatrix[i];
 }
 delete[] myMatrix;
//looked around for examples, but were all different enough to not help
//

时间: 原作者:

0 0

//delete[] myMatrix[i][j]; (tried this method, did not work)

你这里的代码


myMatrix[i][j] = rand();

不为 myMatrix[i][j] ( 它是一个非指针类型,但它是一个简单的int ) 分配任何新堆内存,而是将 rand()的结果指定为值。

因此,这不是必要的/错误,你曾经给 delete 打电话。


你只会将 delete/delete[] 作为 new/new[]的对应项调用,因为它们被分配给。

另外,为了从内存管理中获得救赎,我将认真推荐使用 C++ 标准容器,比如 std::vector<std::vector<int>> myMatrix; 而不是管理原始指针。

原作者:
...