简体   繁体   中英

function to insert an element in sorted array in C

I am new to C and was writing a function to insert an element to sorted list. But my code does not display the last digit correctly. Though i know there are variety of ways to correct it but i want to know why my code isnt working, here's the code

#include <stdio.h>
int insert(int array[],int val);
int main (void)
{
  int arr[5],j;
  for (j = 0; j<5; j++)
  {
    scanf("%d",&arr[j]);
  }

  insert(arr,2);
  for(j = 0;j<6;j++)
    printf("%d",arr[j]);
return(0);
}
int insert(int array[],int val)
{
  int k,i;
  for (k = 0;k<5;k++)
    if(val<array[k])

    break;

  for (i = 4; i>=k;i--)
  {
    array[i+1] = array[i];

  }
  array[k] = val;

  return(1);

}

You are writing out of the range of the array here:

for (i = 4; i>=k;i--)
{
    array[i+1] = array[i];

Where i+1 == 5 and you array has a range of 0 ... 4

Then you try to print the array but you go out of bounds again:

for(j = 0;j<6;j++)
    printf("%d",arr[j]);

First make sure your array is large enough.

When you give a static / auto array to a function for insertion of elements, you must give: Address, Valid length, and Buffer Space unless guaranteed large enough.

When giving a dynamically allocated array, you must give pointer and valid length, you might give buffer space or guarantee enough space left to avoid reallocations.

Otherwise, you risk a buffer overrun, and UB means anything may happen, as in your example.

You're trying to make arr[6] out of arr[5] adding one val - it's impossible in C using statically allocated arrays. To accomplish what you're trying to do you'd need to use dynamical arrays allocation:

int *arr;
int N = 5;
arr = (int *)malloc(N*sizeof(int));

then you use this arr same way as you did with arr[5] for loading data here via scanf. And later on , while adding extra value to array - you'd need to reallocate your arr to make it bigger (read about malloc/realloc C functions):

arr = (int *)realloc((N+1)*sizeof(int));

Now your arr is of 6 int-s size. Unfortunately if you don't know array sizes (number of elements) a priori you would need to deal with dynamical memory allocations in C.

Don't forget to release that memory in the end of the main() function:

free(arr); 

You have to increase your array size from 5 to 6 as you are inserting one new element in your array, so there should be some space for that.

int arr[6];

you can also find more information in the link below: https://learndswithvishal.blogspot.com/2020/06/insert-element-in-sorted-array.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM