c++ - 使用 new 调整数组大小

标签 c++ pointers new-operator

所以我试图通过调用 ResizeArray() 函数来调整数组的大小。但是,我不知道在这种情况下使用“删除”的正确方法是什么。 (我创建了一个新的 int * 并将值从原来的值复制到它然后我让原来的指针指向新的,现在我不知道要“删除”什么

    class Base

        {
    private:
        int sizeInClass;
        int *arrayy=nullptr;

    public:
            Base(int s)
            {
             sizeInClass=s;
             arrayy = new int[s]{};
             setValue();
            };
        void setValue()
        {
             for(int x=0;x<sizeInClass;x++)
             {
             arrayy[x]=x;
             }
        }

        void print()
        {
             int countter=0;
             for(int x=0;x<sizeInClass;x++)
             {
             countter++;
             cout<<arrayy[x]<<endl;
             }
             cout<<"The size of the array is : "<<countter<<endl;
        }


        void ResizeArray(int newSize)
        {
            int *newArray = nullptr;

            newArray = new int[newSize];

                for(int x=0;x<sizeInClass;x++)
                {
                    newArray[x]=arrayy[x];
                }

            delete [] arrayy;    /////////////////////////////////// should i use deleate here ? 

            arrayy = newArray;

            delete [] newArray; /////////////////////////////////// or should I use deleate here ?

            sizeInClass = newSize;
        }



        ~Base()
        {
        delete [] arrayy;  /////////////////////////////////// or just use delete here
        arrayy=nullptr; 
        }

};


int main()
{

   Base b(5);
   b.print();
   b.ResizeArray(8);
   b.setValue();
   b.print();

    return 0;

}

最佳答案

您建议的第一个和第三个 delete 是正确的。

关于c++ - 使用 new 调整数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58350258/

相关文章:

c++ - 使 QTreeWidget 项目在拖放时展开

c++ - 初始化常量变量并在失败时断言 (c++)

c++ - 在 C++ 中将字节序列重复到更大缓冲区的最简单方法

c++ - 为什么用点运算符的值在C++中没有更改?

c++ - delete 和 delete[] 的确切行为是什么?

c++ - 函数中的 "New"和 "delete"

c++ - 我的射弹更新功能有什么问题?

c - 使用 Malloc 并在函数之间分配给数组

c - 我无法理解这个程序的输出

javascript - 对使用 `map` 创建的数组上 `new` 的行为感到困惑