向动态数组添加值

时间:2014-01-31 06:26:32

标签: c++ dynamic-arrays

所以我有这个代码,但是在添加第4个值之后它没有输出正确的东西,就像它全部被删除而且直到下次运行才会被添加

#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');
}

2 个答案:

答案 0 :(得分:4)

您可以而且应该使用std::vector<int>data这一事实将作为指针按值传递

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

(对于int data[],请阅读int* data)。所以`addValue有自己的指针副本,无论它对它做什么对调用者都没有影响。您可以通过引用传递指针来解决此特定问题:

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

答案 1 :(得分:1)

通过reference传递data。你是按价值传递的。