Hello I am trying to allocate a dynamic array of length that the user inputs. I have a function to this for me but it doesn't allocate the number that I want it to allocate. For example, when I input one it gives me 7 digits...

heres the code:

int* Allocate(int& digits)
{
    cout << digits << endl;
    int* hold;
    hold = new int[digits];

    for (int i = 0; i < digits; i++)
    {
        cout << *hold;
        hold++;
    }
    cout << endl;

    return hold;
}

I can't find out anything thats wrong. The number of digits is getting passed correctly..,

Array hold is created but not initialised with any values. When you dereference hold, it spits out garbage value.

You must initialize int array hold first after dynamically allocating it.

I do have an Initializer function as well but when I output that it gives me double the number I inputed, and its all garabage values instead of 0 as defined in this function (you may not understand why I am doing it like this but it is part of a bigger program):

void Init(int* array, int& digits)
{
    for (int i = 0; i < digits; i++)
    {
        *array = 0;
        array++;
    }
    for (int i = 0; i < digits; i++)
    {
        cout << *array;
        array++;
    }
    cout << endl;
}

Nevermind, it all worked out.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.