C语言中什么是数组越界索引?
假设您有一个包含四个元素的数组。那么,数组索引将从 0 到 3,即我们可以访问索引 0 到 3 的元素。
但是,如果我们使用大于 3 的索引,则称为数组越界索引。
如果我们使用超出范围的数组索引,则编译器将编译甚至运行。但是,不能保证结果的正确性。
结果可能不确定,并且会开始导致许多问题。因此,建议在使用数组索引时要小心。
示例程序
以下是数组中超出范围索引的 C 程序:
#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
",i,std[i]);
return 0;
}输出
当执行上述程序时,会产生以下结果:
std[0]: 100 std[1]: 200 std[2]: 300 std[3]: 400 std[4]: 2314
解释
在这个程序中,数组大小为 4,所以数组索引将从 std[0] 到 std[3]。但是,这里我们将值 500 赋给了 std[4]。
因此,程序成功编译并执行。但是,在打印值时,std[4] 的值为垃圾数据。我们为其分配了 500,结果为 2314。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP