Question

So I have this code, but it is not outputting, after adding 4th value, the right stuff, it's like it all gets deleted and it is not added until the next run

#include <iostream>

using namespace std;

const int DEFAULT_CAPACITY = 2;

void addValue(int data[], int& logSize, int& physSize, int newValue)
{
    // DATA DICTIONARY
    int *temp;

    if (logSize == physSize)
    {
        physSize *= 2;
        temp = new int[physSize];

        for (int i = 0; i <= logSize; i++)
        {
            temp[i] = data[i];
            cout<<temp[i]<<endl;
        }

        delete [] data;
        data = temp;
    }

    data[logSize] = newValue;

    for (int i = 0; i <= logSize; i++)
    {
        cout<<data[i]<<endl;
    }

    logSize++;
}

void printData(int data[], int logSize)
{
    cout<<endl;
    cout<<"ARRAY DATA:"<<endl;

    for (int i = 0; i < logSize; i++)
    {
        cout<<data[i]<<endl;
    }
}

void main()
{
    //DATA DICTIONARY
    int *data;
    int logSize;
    int physSize;
    int newValue;
    char choice;

    physSize = DEFAULT_CAPACITY;
    logSize = 0;
    data = new int[physSize];

    do
    {
        cout<<"What would you like to do?"<<endl;
        cout<<"(A)dd value to array"<<endl;
        cout<<"(D)isplay all values"<<endl;
        cout<<"(Q)uit"<<endl;

        cin>>choice;

        if (choice == 'A' || choice == 'a')
        {
            cout<<"What integer do you want to add? ";
            cin>>newValue;
            addValue(data, logSize, physSize, newValue);
        }

        if (choice == 'D' || choice == 'd')
        {
            printData(data, logSize);
        }

        cout<<endl;

    } while (choice != 'Q' && choice != 'q');
}
Was it helpful?

Solution

The fact that you could and should use an std::vector<int> aside, data is being passed as a pointer by value here:

void addValue(int data[], int& logSize, int& physSize, int newValue)

(for int data[], read int* data). So `addValue has its own copy of the pointer, and whatever it does with it has no effect on the caller side. You can fix this particular problem by passing the pointer by reference:

void addValue(int*& data, int& logSize, int& physSize, int newValue)

OTHER TIPS

Pass the data by reference. You are passing it by value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top