What is out of bounds index in an array - C language?

Suppose you have an array with four elements. Then, an array indexing will be from 0 to 3, i.e., we can access elements from index 0 to 3.

But, if we use index which is greater than 3, it will be called as an index out of bounds.

If, we use an array index which is out of bounds, then the compiler will compile and even run. But, there is no guarantee for the correct result.

Result can be not sure and it will start causing many problems. Hence, it is advised to be careful while using an array indexing.

Example Program

Following is the C program for an index out of bounds in an array −

 Live Demo

int main(void){
   int std[4];
   int i;
   std[0] = 100; //valid
   std[1] = 200; //valid
   std[2] = 300; //valid
   std[3] = 400; //valid
   std[4] = 500; //invalid(out of bounds index)
   //printing all elements
   for( i=0; i<5; i++ )
      printf("std[%d]: %d
",i,std[i]);    return 0; }


When the above program is executed, it produces the following result −

std[0]: 100
std[1]: 200
std[2]: 300
std[3]: 400
std[4]: 2314


In this program, an array size is 4, so the array indexing will be from std[0] to std[3]. But, here, we have assigned the value 500 to std[4].

Hence, program is compiled and executed successfully. But, while printing the value, the value of std[4] is garbage. We have assigned 500 in it and the result is 2314.