0
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?

2
  • 1
    When you create the new array and copy the old one, the old one still has the same values. Commented Sep 28, 2014 at 21:09
  • 1
    You can use std::vector which already has functionality to insert in the middle. Commented Sep 28, 2014 at 21:18

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

6 Comments

It did not work and all printed values became garbage.
Did you make all 3 changes above exactly as posted ?
the first change gave the error "unresolved externals" in VS2013.
You probably forgot to change the function prototype ?
No - the prototype needs to match the function, so it should be: void insert(int*&, int, int); - no changes needed when calling the function - see link to live demo in answer above.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.