使用带动态数组的指针的问题

时间:2013-11-11 20:48:07

标签: c++ arrays pointers

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

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

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

现在我的输出正在阅读各种各样的螺丝。我知道这与指针有关,但我现在处于亏损状态。

Infile:

3
456
593
94
58
8
5693
211

输出:

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

collections.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 add:

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 print:

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

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

1 个答案:

答案 0 :(得分:3)

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

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

从最后一行移除int *,其余的看起来没问题。

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