Home >Backend Development >C++ >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.
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; }
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
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!