c语言中数组越界怎么办
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.
假设您有一个包含5个元素的数组,那么数组索引将从0到4,即我们可以访问从索引0到4的元素。
But, if we use index which is greater than 4, it will be called index out of bounds.
但是,如果我们使用大于4的索引,它将被称为索引超出范围。
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).
在程序中,数组大小为5,因此数组索引将从arr [0]到arr [4] 。 但是,在这里,我为arr [5]分配了值60( arr [5] 索引超出范围数组索引 )。
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).
程序已成功编译并执行,但是在打印该值时, arr [5]的值是不可预测的/垃圾。 我在其中分配了60,结果是11035(可以是任何值)。
翻译自: https://www.includehelp.com/c/out-of-bounds-index-in-an-array-in-c.aspx
c语言中数组越界怎么办