Home » C programming language

What happens if we use out of bounds index in an array in C language?

Out of bounds array indexing in C programming language: Here, we will learn that what happens if we use out of bound array indexing in C language?
Submitted by IncludeHelp, on May 28, 2018

Let’s understand first, what is index out of bounds?

Let suppose you have an array with 5 elements then the array indexing will be from 0 to 4 i.e. we can access elements from index 0 to 4.

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

If we use an array index that is out of bounds, then the compiler will probably compile and even run. But, there is no guarantee to get the correct result. Result may unpredictable and it will start causing many problems that will be hard to find.

Therefore, you must be careful while using array indexing.

Consider the example:

#include <stdio.h>

int main(void) 
	int arr[5];
	int  i;
	arr[0] = 10;  //valid
	arr[1] = 20;  //valid
	arr[2] = 30;  //valid
	arr[3] = 40;  //valid
	arr[4] = 50;  //valid
	arr[5] = 60;  //invalid (out of bounds index)
	//printing all elements
	for( i=0; i<6; i++ )
		printf("arr[%d]: %d\n",i,arr[i]);

	return 0;


    arr[0]: 10
    arr[1]: 20
    arr[2]: 30
    arr[3]: 40
    arr[4]: 50
    arr[5]: 11035


In the program, array size is 5, so array indexing will be from arr[0] to arr[4]. But, Here I assigned value 60 to arr[5] (arr[5] index is out of bounds array index).

Program compiled and executed successfully, but while printing the value, value of arr[5] is unpredictable/garbage. I assigned 60 in it and the result is 11035 (which can be anything).

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

© https://www.includehelp.com (2015-2018), Some rights reserved.

close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.