I've a question on dynamic memory.
As i understand it, i can create a dynamic memory array using:
xxx= new int [z];

Then I can set the value of 'z' to be whatever value i want during the program.

But if i create a dynamic memory array using a predefined length, eg.
xxx = new int [5]
is the array limited to just 5 values or can i add more elements to the array?

Thanks.

You're misunderstanding somewhat. It is not possible to simply resize a 'raw' array (Whether it is created by new or as an ordinary array object).

Once an array is created in memory, it can't be extended - The reason being that you have no control over the layout of objects in memory. Arrays must be contiguous (that means they must be stored as one "chunk"), and there's nothing stopping your O/S from sticking a different object after the end of your array - therefore 'resizing' an array actually involves creating a new one, copying its contents (to the new, bigger chunk) and then destroying the old one.


If you wish to use a resizable array, then your best option is a vector. vectors are resizable because they do all of the create/copy/destroy internally without you needing to manage it yourself. The interface to a vector is based on arrays (meaning you can use the [] syntax which you're used to) - there are also other useful features of vectors, such as it knowing its own size, and being usable with other parts of the C++ standard library.

#include <vector>

int main()
{
    // create an 'array' with 3 items
    std::vector<int> my_array(3);

    my_array[0] = 1;
    my_array[1] = 2;
    my_array[2] = 3;

    // resize it by adding a new one
    my_array.push_back(4);
}
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.