Home > Backend Development > C++ > body text

In C language, what is an out-of-bounds index of an array?

WBOY
Release: 2023-08-27 21:05:05
forward
1212 people have browsed it

In C language, what is an out-of-bounds index of an array?

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

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

If we use an out-of-bounds array index, the compiler will not compile or even run. However, the results are not guaranteed to be correct.

The results may be uncertain and cause many problems. Therefore, it is recommended to be careful when using array indexes.

Sample program

The following is a C program where the index in the array is out of bounds-

Live demonstration
#include<stdio.h>
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</p><p>",i,std[i]);
   return 0;
}
Copy after login

Output

When the above program is executed When, the following result will be produced -

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

Explanation

In this program, the array size is 4, so the array index will be from std[0] to std[3]. However, here we assign the value 500 to std[4].

Therefore, the program was successfully compiled and executed. However, when printing the value, the value of std[4] is garbage. We allocated 500 in it and the result is 2314.

The above is the detailed content of In C language, what is an out-of-bounds index of an array?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!