×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

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;
}

Output

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

Explanation:

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).




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.