c语言中数组越界怎么办_如果我们使用C语言数组中的越界索引怎么办?

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语言中数组越界怎么办

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值