簡體   English   中英

在C ++中使用指針刪除數組-多維和多指針-

[英]Deleting Arrays With Pointers--Multidimensional and Multipointer---in C++

因此,我知道多個維度/數組會引起混淆,但是如何正確刪除這些類型的數組? 我知道語法,但是添加多個維度/指針會比較棘手。 這是一些代碼片段:

  //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 ++標准容器,例如std::vector<std::vector<int>> myMatrix; 而不是管理原始指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM