0

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..,

Edited by ShEeRMiLiTaNt

2
Contributors
3
Replies
4
Views
4 Years
Discussion Span
Last Post by ShEeRMiLiTaNt
0

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.

0

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;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.