2

我正在从 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

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

4

1 回答 1

3

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

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

int *从最后一行中删除,其余的看起来还可以。

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

于 2013-11-11T20:52:58.487 回答