Search code examples
arrayscfor-loopinsertdynamic-memory-allocation

Insertion of element in the array-


I'm not so good with C so please help me in this project where I want the user to pick what operation he wants to perform, where I just completed the insertion part of it and here the code is giving the garbage values after the insertion. This is my code so far-

#include<stdio.h>
#include<stdlib.h>

int main(){
    int n, opt, i, insOpt, pos, newEle;
    printf("Enter the number of elements you want to store in the array: ");
    scanf("%d", &n);
    int* arr = (int*) malloc(n*sizeof(int));
    printf("Enter all %d elements you want to store in the array: ", n);
    for(i=0; i<n; i++){
        scanf("%d", &arr[i]);
    }

    options:
    printf("Enter the operation you want to perfrom: \n 1. Insertion \n 2. Deletion \n 3. Traversing \n 4. Searching \n 5. Sorting \n 6.Reverse of array \n");
    scanf("%d", &opt);
    switch (opt)
    {
    case 1:
        n++;
        int* newArr=(int*) realloc(arr, n*sizeof(int));
        for(i=0; i<n-1; i++){
            newArr[i] = arr[i];
        }
        free(arr);
        arr = newArr;
        printf("Pick where you want to insert: \n 1. Beginning \n 2. Middle \n 3. End \n 4. Position");
        scanf("%d", &insOpt);
        switch (insOpt)
        {
        case 1:
            pos=0;
            break;
        case 2:
            //
            break;
        case 3:
            pos=n;
            break;
        case 4:
            printf("Enter the position: ");
            scanf("%d", &pos);
            break;
        default:
            printf("Please pick between 1 to 4: ");
            break;
        }
        printf("Enter the element: ");
        scanf("%d", &newEle);
        for(i=n-1; i>=pos-1; i--){
            arr[i]=arr[i-1];
        }
        arr[pos-1] = newEle;
        printf("Array after insertion: ");
        for(i=0; i<n; i++){
            printf("%d ",arr[i]);
        }
        break;
    
    default:
        break;
    }

    return 0;
}

Now, when I try to insert the element at the beginning it gives me some random values after 8-

Array after insertion: 8 1512474568 5 1571285629 1432712575 3


Solution

  • For starters this code snippet

        for(i=0; i<n-1; i++){
            newArr[i] = arr[i];
        }
        free(arr);
    

    does not make sense. The reallocated array already contains existent elements and the pointer arr in this case is invalid. So remove this code snippet.

    If the user selected the end position then the value of pos shall be n - 1 instead of n. on the other hand, if the user selected the position in the beginning of the array then pos shall be equal to 0.

    In this case the following for loop will look like

        for ( i=n-1; i != pos; i--){
            arr[i] = arr[i-1];
        }
        arr[pos] = newEle;