Edison
Edison

Reputation: 4291

Insert element in array

void insert(int*arr, int element,int index)
{
    if (index < SIZE)
    {
        arr[index] = element;
    }
    else
    {
        int* new_array = new int[SIZE + 1];
        int i = 0;
        for (i = 0; i < SIZE; i++)
        {
            new_array[i] = arr[i];
        }
        new_array[i] = element;
        SIZE++;
        printArray(new_array);
    }



}

I have made an insert function in C++ that will insert values at specific indices of the array.After index gets increased I made a new array and copied values from the smaller array into it. Problem is that printArray function which is just looping to print the array does well when it is called inside the insert function otherwise when I called printArray from the main last value of the array was garbage why is that?

Upvotes: 0

Views: 6756

Answers (1)

Paul R
Paul R

Reputation: 212979

You need to delete the old array and return the new array in its place, e.g.:

void insert(int* &arr, int element, int index) // <<< make `arr` a reference so that we can modify it
{
    if (index < SIZE)
    {
        arr[index] = element;
    }
    else
    {
        int* new_array = new int[SIZE + 1];
        for (int i = 0; i < SIZE; i++)
        {
            new_array[i] = arr[i];
        }
        new_array[SIZE] = element;
        SIZE++;           // <<< NB: using a global for this is not a great idea!
        delete [] arr;    // <<< delete old `arr`
        arr = new_array;  // <<< replace it with `new_array`
    }
}

LIVE DEMO

Note that all this explicit low level management of your array goes away if you start using proper C++ idioms, such as std::vector<int> instead of C-style int * arrays.

Upvotes: 4

Related Questions