将指针与动态数组一起使用时出现问题

Problems using pointers with an dynamic array

本文关键字:问题 一起 指针 动态 数组      更新时间:2023-10-16

我正在从infile中读取整数并使用指针将它们添加到int数组中。

我已经多次跟踪代码,一切似乎都在逻辑上流动,并且在编译器中没有收到任何语法错误或警告,所以我不确定出了什么问题。

该程序要求我们使用数组而不是向量,否则我认为我不会遇到这些问题。

现在我的输出正在阅读各种拧巴。我知道这与指针有关,但我现在不知所措。

文件:

3
456
593
94
58
8
5693
211

输出:

The items in the array are as follows.
7476376, 7475472, -17891602, 17891602, -17891602, -17891602, -17891602, -178916

集合.h

class collections
{
    public:
        collections();
        void add(int);  //adds the value to the array.
        void print();  //prints item of the array comma separated.
        ~collections();
    protected:
        int arraySize;
        int *array;
};

构造 函数:

collections::collections()
{
    arraySize = 1;
    array = new int[arraySize];
}//done

无效添加:

void collections::add(int value) //adds the value to the array.
{
    //initial add to master array.
    if (arraySize == 1)
    {
        array[0] = value;
        arraySize++;
    }
    //every other add to master array.
    else
    {
        //temp array.
        int *tempArray = new int[(arraySize)];
        //copies old array into temp array.
        for (int i = 0; i < arraySize-1; i++)
        {
            tempArray[i] = array[i];
        }
        //adds new incoming value to temp array.
        tempArray[(arraySize-1)] = value;
        //new master array
        delete [] array;
        int *array = new int[arraySize];
        //copies temp to master array.
        for (int j =0; j < arraySize; j++)
        {
            array[j] = tempArray[j];
        }
        //cleanup
        delete [] tempArray;
        arraySize ++;
    }
} //done

无效打印:

void collections::print() //prints item of the array comma separated.
{
   cout << "The items in the array are as follows.n";
    for (int i = 0; i < arraySize; i++)
    {
        cout << array[i] << ", ";
    }
}//done

对不起,我知道这可能很简单,但对于我的生活,我看不到问题所在。

您不小心声明了覆盖类成员的array的本地副本:

//new master array
delete [] array;
int *array = new int[arraySize];
^^^^^

从最后一行中删除int *,其余部分看起来没问题。

PS:你考虑过使用std::vector<int>吗?