Hi I've been struggling with this for a very long time now. And I can't seem to get it done.

I want to make an array, dynamic allocted array. Which act something like an vector (I know c++ has vector). So my approach was to create a list_add() function. Its purpose is to add new integer values to the array, and to increase the array size if it hits end of it.

Here's the problem. What I want to do in the code is to create a new dynamic allocated array, and rellocate the values from the old array to the new one. After that I want the new array to be recognized as the old one. However it does not seem to do it.

Can anyone point out to be if this is the correct approach, and what I did wrong in the code?

This is the test main

int main()
    const int N = 7;

    //declaring dynamic array allocation
    int* list = new int[N];

    int used = 0;//, a_val;

    //and some scrap values
    for(int i=0;i<11;i++)
        list_add(list, used, N, i);

    cout << endl << "Size: " << N << endl << endl;
    cout << "Prints the list " << endl;
    for(int i=0;i<used;i++)
        cout << list[i] << ". ";


This is the function

bool list_add(int list[], int& space_used, int max_size, int value)

    if(max_size-space_used > 0)
        list[max_size-space_used-1] = value;
        return true;
        cout << "Increasing size of array!" << endl;
        int new_max_size = space_used+1;

        int *list_new = new int[new_max_size];
        //this loop is only to check whether values are copied to the new array with bigger size.
        for(int i=0; i<new_max_size; i++)
            list_new[i] = i;
            cout << list_new[i] << ". ";
        delete [] list;
        cout << endl;
        list = list_new;
        return false;

Recommended Answers

All 2 Replies

list = list_new; doesn't work. It results in the "shallow copy" where just the pointer is transferred. You need to copy it elementwise.

This is when you can use a pointer that takes an refrence.

Try adding this :

bool list_add(int (&list)[], int& space_used, int max_size, int value)

Now list is an reference variable which happens to be an array.

Also only incrementing max_size by 1 is a bad idea. Try doubling it.
In fact do a test and see how much faster doubling the max_size is.
The STL vectors uses this idea.

Be a part of the DaniWeb community

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