在C++中删除带指针的数组——多维和多指针数组

Deleting Arrays With Pointers--Multidimensional and Multipointer---in C++

本文关键字:数组 指针 C++ 删除      更新时间:2023-10-16

所以我知道多个维度/数组可能会令人困惑,但我如何正确删除这些类型的数组?我知道语法,但添加多个维度/指针会很棘手。以下是一些代码片段:

  //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
  //
//  delete[] myMatrix[i][j]; (tried this method, did not work)

你这里的代码

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

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

因此,这不是必要的/错误的,你可以为它调用delete


您只调用delete/delete[]作为new/new[]的对应方,调用顺序与它们的分配顺序相反。

此外,为了从内存管理的困境中解脱出来,我强烈建议使用像std::vector<std::vector<int>> myMatrix;这样的c++标准容器,而不是管理原始指针。