尝试使用C 中的动态数组来推动值

Trying to push a value using a dynamic array in c++

本文关键字:数组 动态      更新时间:2023-10-16

我正在尝试编写一个将项目推到我动态分配的数组末端的函数(不允许使用向量)。如果列表太小而无法存储下一个数字,则一旦到达列表的大小加倍,一切都将变成地狱,并开始从计算机上喂我随机数。谁能看到为什么它不像适合使用的那样加倍?

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

如果这是您的初始设置:

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

那么,您的代码很可能是第一次执行内存访问违规行为:

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

如Barak所暗示的,需要初始化contents_指针。如果没有,C 将将其指向您可能不希望的东西。