Hey folks,

First poster here :icon_cheesygrin:

So we got an assignment and part of it is, to write a stack with an array.
So far so good, but I'd like to use a dynamic array that doesn't need the user to input any size.

void init() {
int i;
cin << i;
int *p_array = new int[i];
}

What would be the proper way of creating a dynamic array that changes its size accordingly to the users needs, without any userinput on that?

What I am wondering is, if I just declare an dynamic array with the size [0], I can still write to [1] for example.

Why would you be able to use more memory than you allocated?

What would be the proper way of creating a dynamic array that changes its size accordingly to the users needs, without any userinput on that?

Use a default size that's reasonably common and increase it as necessary.

Why would you be able to use more memory than you allocated?

Yea, I messed that up, already removed that bit. Seemed to be working at first.

And how do I increase the size of an dynamic array when needed?

And how do I increase the size of an dynamic array when needed?

C++ doesn't have a version of realloc() that pairs with new[] and delete[], so your only option is to allocate a new array of the larger size, copy the existing elements to that new array, then release the old array:

int *resize_array(int *old_array, int old_size, int new_size)
{
    if (old_size >= new_size)
        return a;

    int *new_array = new int[new_size];

    for (int i = 0; i < old_size; i++)
        new_array[i] = old_array[i];

    delete[] old_array;

    return new_array;
}

Don't forget to use the new address, so all pointers to and into the old array must be assumed to be invalidated by the resize.

Alright, thats a function pointer right?
Well that's part of tomorrows lecture, thanks anyway. Probably gonna use a static array for now.

Alright, thats a function pointer right?

No, it's a function that returns a pointer.

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.