Search code examples
c++arraysinsertpositionelement

insertElement() function doesn't work as intended


I'm having an issue in my program with my insertElement() function. What I had intended insertElement to do is to take the index from the prototype and move all the values to the right, including the value on that index, to the right ONCE. So, If I were to have my array {1, 2, 3, 4} and I wanted to insert the value "10" at the index "2", the resulting array would be {1, 2, 10, 3, 4}.

I know I'd have to tweak my insertElement() function to fix this issue, but I'm not sure where to start, could anybody give me a hand? Here is my code:

#include <iostream>
using namespace std;

const int CAPACITY = 20;

void displayArray(int array[], int numElements)
{
    for (int i = 0; i < numElements; i++)
        cout << array[i] << " ";
    cout << endl;
}

bool insertElement(int array[], int& numberElements, int insertPosition, int insertTarget)
{
    int p = 0;
    int j = 1;
    int arrayPositionFromLast = (numberElements-1);
    if (numberElements>=CAPACITY)
    {
        cout << "Cannot insert an element, array is full." << endl;
        return false;
    } else {
        for (int i=arrayPositionFromLast; i>insertPosition; i--)
        {
            array[arrayPositionFromLast-p]=array[arrayPositionFromLast-j];
            p++;
            j++;
        }
        array[insertPosition] = insertTarget;
    }
    return true;
}

int main()
{
    int array[6] = {1, 2, 3, 4, 5, 6};
    int numArrayElements = 6;
    int endOfArrayValue, insertedValue, insertedValuePosition;

    cout << "Enter a value and a position to insert: ";
    cin >> insertedValue >> insertedValuePosition;

    insertElement(array, numArrayElements, insertedValuePosition, insertedValue);
    displayArray(array, numArrayElements);
}

Solution

  • first you should define your array with CAPACITY

    int array[CAPACITY] = {1, 2, 3, 4, 5, 6};
    

    You can move your data with memmove.

    if (numberElements>=CAPACITY)
    {
        cout << "Cannot insert an element, array is full." << endl;
        return false;
    } else {
       memmove(array + insertPosition+ 1, array + insertPosition, (numberElements - insertPosition) * sizeof (int));
       array[insertPosition] = insertTarget;
    }