【问题标题】:Trying to push a value using a dynamic array in c++尝试在 C++ 中使用动态数组推送值
【发布时间】:2014-01-29 23:22:14
【问题描述】:

我正在尝试编写一个将项目推送到动态分配数组末尾的函数(不允许使用向量)。如果列表太小而无法存储下一个数字,一旦它进入该区域以使列表的大小增加一倍,这一切都变得糟糕透顶,并开始从计算机向我反馈随机数。谁能明白为什么它没有像预期的那样翻倍?

    int *contents_;
    int *temp;
    int size_ = 0;
    int capacity_ = 1;


    void pushBack(int item) /**appends the specified value to DynArray; if the contents array is full,
    double the size of the contents array and then append the value **/
    {
        if (size_ == capacity_)
        {
            capacity_ = (2*capacity_);
            temp = new int[capacity_];
            for (int i = 0; i < size_; ++i)
            {
                temp[i] = contents_[i];
            }
            delete [] contents_;
            contents_ = temp;
        }
        contents_[size_++] = item;

    }

编辑 ** 我忘了说。这是一个类外的功能。这是在标题和主要:

 main()
{
DynArray myArray;
myArray.pushBack(2);
myArray.pushBack(3);

myArray.printArray();

return 0;
}

【问题讨论】:

  • 如何初始化和使用这个?
  • 如果这是家庭作业,我认为数组不算作列表。

标签: c++ arrays memory dynamic push


【解决方案1】:

如果这是您的初始设置:

int *contents_; // Junk
int size_ = 0;
int capacity_ = 1;

那么您的代码很可能在第一次执行时就执行了内存访问冲突:

if (size_ == capacity_)
{
     // Not entering here, contents_ remains junk
}
contents_[size_++] = item;

【讨论】:

    【解决方案2】:

    正如 barak 所暗示的,contents_ 指针需要被初始化。如果没有,c++ 会将它指向你可能不希望它指向的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2018-09-05
      • 1970-01-01
      相关资源
      最近更新 更多