-2
#include <stdio.h>

int main()
{
int arr[5], size, i, pos, elem;

printf("Enter the size of array(less than 100)\n");
scanf("%d",&size);

printf("\nEnter the elements of array one by one\n");

for ( i = 0; i < size; i++)
scanf("%d",&arr[i]);

printf("\nEnter the position of insertion\n");
scanf("%d",&pos);

printf("\nEnter the element\n");
scanf("%d",&elem);

for ( i = size - 1 ; i >= pos - 1; i--)
    arr[i + 1] = arr[i];

arr[pos - 1] = elem;

printf("\nInserted array is\n");

for ( i = 0; i <= size; i++)
    printf("\t%d",arr[i]);
    printf("\n");



return 0;
}

Since the array is int arr[5] it shouldn't be possible to insert an element at any index not in range [0,1,2,3,4]. Why am I able to insert at arr[6] and get correct answer still?.

Mann
  • 1
  • 5

2 Answers2

1

Accessing array out of bound leads to undefined behvaior.

You might see it working sometimes and might not work sometimes.(You might end up with a crash even)

So just go by the standard and stop accessing array out of bound. Get rid of the undefined behavior

Gopi
  • 19,784
  • 4
  • 24
  • 36
0

You are writing to memory that you did not allocate. Eventually, when you hit memory that you do not have write permissions for, you will get a segmentation fault.

C/C++ doesn't do bounds checking for you like other languages such as Java. It leaves it to the operating system to figure out when you're accessing memory you're not supposed to.

Kacy
  • 3,330
  • 4
  • 29
  • 57