【问题标题】:Program stopped working and giving garbage value C++程序停止工作并给出垃圾值 C++
【发布时间】:2020-03-01 01:44:46
【问题描述】:

我正在为动态数组制作一个程序,我在其中实现了三种方法。 push_back(arguments...),pop_back(arguments...) 和 printArray(arguments...)。

但是当我增加数组的大小时,它会在该索引处给出垃圾值,如果我为超过 15 个值运行代码,它就会停止工作。

#include<iostream>
using namespace std;

void push_back(unsigned int value,unsigned int *array,int &arraySize,int &totalArrayItems ){
  if(arraySize>totalArrayItems){
    array[totalArrayItems]=value;
    totalArrayItems=totalArrayItems+1;
    cout<<"Current size: "<<arraySize<<endl;
  }
  else if(arraySize==totalArrayItems){
      cout<<"Adding the Size of Array... \n";

    unsigned int *tempArray=new unsigned int[arraySize+5];//making new array as asked in requirements
    for(int i=0;i<arraySize;i++){

      tempArray[i]=array[i];
      cout<<"Value in Temp : "<<tempArray[i]<<endl;
    }
    unsigned int *temp=array;
    array=tempArray;
    arraySize=arraySize+5;
    cout<<"Saving "<<value<<" at Position: "<<totalArrayItems<<endl;
    array[totalArrayItems]=value;//adding the new value
    cout<<"Value in Temp "<<totalArrayItems<<" : "<<tempArray[totalArrayItems]<<endl;
    totalArrayItems=totalArrayItems+1;
    cout<<"Updated size: "<<arraySize<<"Current value: "<<value<<endl;
    delete []temp;//delete old array

  }


}
void pop_back(unsigned int *array,int &arraySize,int &totalArrayItems){
  if(totalArrayItems>0){
    totalArrayItems=totalArrayItems-1;
    if(totalArrayItems<(arraySize-5)){
        unsigned int *tempArray=new unsigned int[arraySize-5];
        for(int i=0;i <= totalArrayItems;i++){
          tempArray[i]=array[i];
        }
        unsigned int *temp=array;
        array=tempArray;
        delete[] temp;
        arraySize=arraySize-5;
    }
  }
}
  void printArray(unsigned int *array,int totalArrayItems){
    for(int i=0;i<totalArrayItems;i++){
      cout<<"Value at "<<i<<" : "<<array[i]<<endl;
    }
  }

【问题讨论】:

  • 你能把你的程序变成minimal reproducible example,并清楚地说明预期的输出是什么——以及它会变成什么?
  • 对不起整个代码。问题是我动态分配内存并将该内存分配回相同的指针。它不会在该索引处存储值并打印垃圾值。如果我运行这个程序超过 15 个值,它就会停止工作。
  • 我确定这是您当前的分析,但是如果您从程序中逐点删除,最终您会找到真正的原因,或者您需要将其缩小得更好。
  • 我以前从未通过引用传递指针,因为我认为指针名称本身就是一个引用,但在这里我应该通过引用传递它。我以前不知道,谢谢你的提示,我会记住的。 :)
  • 这对我来说是新的学习。谢谢:)

标签: c++ arrays dynamic


【解决方案1】:

push_back 中的unsigned int* array 是一个局部变量。当您为其分配新值(指向新内存位置的新指针)时,它不会以您调用它的任何方法更新 array 的值。

传递一个指向 int* 的指针,而不是:int**,如果您希望重新分配保持不变。

【讨论】:

  • 非常感谢!它起作用了,我现在接受指针的引用并且它起作用了。
猜你喜欢
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多