簡體   English   中英

指針數組,刪除並分配 C++ 中的指針

[英]Pointers array, deleting and asigning to it pointers in C++

我的問題是當我聲明一個數組 int** arr =new* int[n] 並且我想為它分配指向數組的指針,然后將該指針更改為另一個指針,該指針是它的值的副本 + 另一個數字,它剎車並出現(可能)無限循環。 你能說一下如何使用一些帶有 c++/c 的低級工具以正確的方式做到這一點,或者你能糾正我的代碼嗎?

附加說明:代碼生成非常簡單的 output 但這並不重要。 我想創建程序以將特定索引指針中的數組指針(int * arr)更改為不同的指針。 但另外指針指向 arrays 中的第一個元素。新舊數組之間的差異(例如在索引中的int**arr中更改為 0)是新元素在新元素上更大(在這種情況下為新數字)。所以這個output 只是檢查它是否有效。

在此處輸入圖像描述

下面是我的整個代碼


#include <iostream>
using namespace std;
void stepwise_fill_array(int ** arr, int N, int index)
{
   for(int j=1;j<=10;j++)
   {
       int* poi=arr[index];//getting pointer to array which i wannna change
       int size=0;
       while(poi){poi++;size++;}//getting size of pointer array from arr
       int* n= new int[size+1];//declaring the new array
       for(int i=0; i<size;i++)//copying from all values from old array to new one
           n[i]=poi[i];
       delete[] poi;    
       n[size]=j;//adding to the end new value
       arr[index]=n;//asigning arr[0] to new  diffrent array
   }
      for(int i=0;i<10;i++)
       cout<<arr[0][i]<<" ";
       //should print 1 2 3 4 5 6 7 8 9 10
}
int main(){
    int N = 10; // how big array should be and how many times it should expand
   int** arr = new int*[N];//declaring our array to pointer
   for(int i=0;i<N;i++)
   {
           arr[i]=nullptr;
   }
   int index =0;//index where I would change the pointer of arr   
  
   stepwise_fill_array(arr,N,index);
}

提前感謝您的幫助:)

你的編碼和解釋問題的風格是悲慘的,但幸運的是我復制了它。 當您嘗試從while(poi){poi++;size++;}獲取大小時,您遇到了麻煩。 在 C\C++ 中,不可能從指向該數組的指針檢查數組的大小 相反,您需要在 function stepwise_fill_array的每次迭代中增加大小。 下面我給你正確的解決方案(代碼中有泄漏,但我對效率沒有太大影響):

void stepwise_fill_array(int **arr, int N, int index)
{
int size = 0;
for (int j = 1; j <= 10; j++)
{
  int *poi = arr[index];      //getting pointer to array which i wannna change
  int *n = new int[size + 1]; //declaring the new array
  for (int i = 0; i < size; i++)
  {
    n[i] = poi[i]; //copying from all values from old array to new one
  }
  n[size] = j;    //adding to the end new value
  arr[index] = n; //asigning arr[0] to new  diffrent array
  size++;
}
for (int i = 0; i < 10; i++)
  cout << arr[0][i] << " ";
//should print 1 2 3 4 5 6 7 8 9 10

}

暫無
暫無

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

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