How can I insert a given element in an array in C?

139 Views Asked by At

Here is the output to the code, the element actually gets inserted in the desired position but the initial value at that particular position in not translated to the next memory block, instead gets rewritten to the same value at the next block as seen in the image. So basically, I am not able to figure out how I could add an element at a given position provided user in a C array, of say integers. The array here is a one dimensional array.

I tried making an insertion function and put in my logic into code, the insertion takes place, but the issue it that when it happens, the pre - existing value at that position gets overwritten instead if just shifting to the right.

// code to insert a specific value in an already existing array at any user specified position

#include <stdio.h>
void creation(int size, int position, int value);
void insertion(int arr[], int size, int position, int value);

int main()
{
    int size, position, value;
    printf("Enter the size of the parent array you wish to create - ");
    scanf("%d", &size);
    creation(size, position, value);
    return 0;
}

void creation(int size, int position, int value)
{
    int arr[size];
    for (int i = 0; i < size; i++)
    {
        printf("Enter the parent array element - ");
        scanf("%d", &arr[i]);
    }
    printf("Parent array created with elements \n");
    for (int i = 0; i < size; i++)
    {
        printf("%d \t", arr[i]);
    }
    printf("\n");
    insertion(arr, size, position, value);
}

void insertion(int arr[], int size, int position, int value)
{
    printf("Enter the position in the parent array where you would like to insert the element - ");
    scanf("%d", &position);
    if (position <= 0 || position > size+1)
    {
        printf("Invalid position entered, cannot add element! \n");
    }
    else
    {
        printf("Enter the value you wish to insert - ");
        scanf("%d", &value);
        for (int i = size-1; i >= position; i--)
        {
            arr[i+1] = arr[i];  // I THINK THIS IS WHERE THE PROBLEM IS ARISING IN THE FINAL ITERATION OF THE LOOP, THE ARRAY BECOMES
                                // BECOMES EMPTY WHICH IS WHY THE VALUE IS GETTING REPEATED
        }
        arr[position-1] = value;
        size += 1;
        printf("Array after insertion successfully \n");
        for(int i = 0; i < size; i++)
        {
            printf("%d \t", arr[i]);
        }
    }
}
2

There are 2 best solutions below

1
HardcoreHenry On

So there's a bunch of issues with this.

First, you generate an array of size size. In C, indexes are 0-based. This means the valid indexes of the array would be arr[0] to arr[size-1]. Specifically arr[size] is not valid, and attempting to write to it causes a memory scribble (i.e., it is undefined behavior). This is important because you have the loop:

        for (int i = size-1; i >= position; i--)
        {
            arr[i+1] = arr[i];
        }

Notice on the first iteration, i=size-1, and thus you're assigning to arr[size-1+1] ==> (arr[size]).

Next, in the following lines:

        arr[position-1] = value;
        size += 1;
        printf("Array after insertion successfully \n");
        for(int i = 0; i < size; i++)
        {
            printf("%d \t", arr[i]);
        }

you increment size, but notice that this does not make the array bigger. The space allocated for the array remains the same. So now, when you do your for loop, you again loop to the new size - 1, which is one to far again.

As far as not inserting the value -- you would need to put some output of some sample data to show exactly what the issue you're facing is.

Finally, your loop should either go to position - 1 (which is the 0-based index of the array) So:

        //                v (note this is -2 here...)
        for (int i = size-2 ; i >= position-1; i--)
        {
            arr[i+1] = arr[i];
        }

or, even better:

        for (int i = size-1; i >= position; i--)
        {
            arr[i] = arr[i-1];
        }

This moves the array element at the desired location

1
Chris On

A couple of additional suggestions as an addendum to HardcoreHenry's answer:

  • You are using variables with indeterminate values when you pass position and value from main to creation and from there to insertion. As a result, code using these exhibits undefined behavior.

  • You should use size_t as your type rather than int when interacting with positions in arrays. Make sure to use the printf format specifier %zu when printing such a value.

  • You are not checking the scanf succeeded in reading a value. This is a very good habit to get into. It will return a value equal to the number of values read. If a valid int was not read in your case, you can try again. Be aware, though, that on an unsuccessful run, scanf leaves the invalid value in the stream to be read again.

  • You should seek to keep functions as tightly focused as possible. A function that inserts a value into an array shouldn't need to do input and output. Decoupling the I/O from this makes it much easier to test your functions and verify they work as expected. Your creation function probably shouldn't be calling insertion either. Let main take care of that.

  • You can replace your function moving values in the array with a single call to memmove.

So an insertion function might look like:

void insertion(int arr[], size_t size, size_t position, int value) {
    if (position >= size) return;

    memmove(
      &arr[position+1], 
      arr[position], 
      sizeof(int) * (size - position - 1)
    );

    arr[position] = value; 
}