指针数组,在 C++ 中删除和分配给它的指针

时间:2021-04-27 15:47:07

标签: c++ arrays dynamic-programming

我的问题是当我声明一个数组 int** arr =new* int[n] 并且我想为其分配指向数组的指针,然后将该指针更改为另一个指针,该指针是它的值的副本 + 另一个number ,它刹车并出现(可能)无限循环。你能说一下如何使用一些带有 c++/c 的低级工具以正确的方式做到这一点,或者你能更正我的代码吗?

附加说明:代码产生了非常简单的输出,但并不重要。我想创建程序来更改特定索引指针中的数组指针(int*arr)到不同指针。但是另外指针指向数组中的第一个元素。此外,新旧数组之间的差异(在索引中的 int**arr 中更改,例如 0)是新元素在新元素上更大(在这种情况下是新数字)。所以此输出仅用于检查它是否有效。

enter image description here

下面是我的全部代码


#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);
}

提前感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

你的编码和问题解释风格很悲惨,幸好我抄袭了。当您尝试从 while(poi){poi++;size++;} 获取大小时,您遇到了麻烦。 在 C\C++ 中不可能从指向这个数组的指针检查数组的大小。相反,您需要在函数 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

}