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語言中數組越界怎么辦