2

I am reading integers from an infile and adding them to an int array using pointers.

I have traced through the code multiple times and everything seems to flow logically and I am not getting any syntax errors or warnings in the compiler so I'm not sure what's wrong.

This program requires us to use arrays and not a vector or else I don't think I would be having these problems.

Now my output is reading all kinds of screwy. I know it has to do with the pointers but I am at a loss at the moment.

Infile:

3
456
593
94
58
8
5693
211

Output:

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

Constructor:

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

Sorry, I know this might be simple but for the life of me I can't see the problem.

1 Answer 1

3

You accidentally declared a local copy of array which overrides the class member:

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

Remove the int * from that last line and the rest looks okay.

PS: Have you considered using std::vector<int>?

Sign up to request clarification or add additional context in comments.

1 Comment

This did it. Thanks. Teacher said not to use vectors on this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.