数组如何定义索引开头_为什么数组索引在C中以0开头?

数组如何定义索引开头

Why array indexing starts with 0 in C, C++, Java and most of other programming languages is one of the common confusion among programmers.

为什么在C,C ++,Java和大多数其他编程语言中,数组索引以0开头是程序员之间常见的困惑之一。

In this article I will tell you the reason behind it.

在本文中,我将告诉您其背后的原因。

Array in C

Image Source

图片来源

为什么数组索引在C中以0开头? (Why Array Indexing Starts with 0 in C?)

Lets try to understand this by taking one example in C. We can declare an array of size 5 in following way.

让我们尝试通过在C中举一个例子来理解这一点。我们可以通过以下方式声明大小为5的数组。

int a[5];

int a [5];

Here a itself is a pointer which contains the memory location of first element of the array.

这里本身就是一个指针,它包含数组第一个元素的存储位置。

Now for accessing the first element we will write a[0] which is internally decoded by compiler as *(a + 0).

现在,为了访问第一个元素,我们将编写a [0] ,它由编译器在内部解码为*(a + 0)

In the same way the second element can be accessed by a[1] or *(a + 1). As a contains the address of first element so for accessing second element we have to add 1 to it. Thats why here we have written *(a +1).

同样,可以通过a [1]*(a + 1)访问第二个元素。 作为包含第一个元素的地址,以便访问第二个元素,我们必须1添加到它。 这就是为什么我们在这里编写*(a +1)

In array the index describes the offset from the first element, i.e. the distance from the first element.

在数组中,索引描述距第一个元素的偏移量,即距第一个元素的距离。

Now lets assume that array indexing starts with 1 instead of 0. In this case for accessing the first element we have to write a[1] which is internally decoded as *(a + 1 – 1).

现在,假设数组索引从1而不是0开始。在这种情况下,为了访问第一个元素,我们必须编写a [1] ,该内部解码为*(a +1-1)

Observe here that we have to perform one extra operation i.e. subtraction by 1. This extra operation will greatly decrease the performance when the program is big.

在这里观察到,我们必须执行一个额外的操作,即减1。当程序很大时,此额外的操作将大大降低性能。

Thats why to avoid this extra operation and improve the performance, array indexing starts with 0 in C, C++, Java, etc.

这就是为什么要避免这种额外的操作并提高性能的原因,在C,C ++,Java等中,数组索引从0开始。

Comment below if you have any queries regarding above article. Do share it if you found this information valuable.

如果您对以上文章有任何疑问,请在下面评论。 如果发现此信息有价值,请共享它。

翻译自: https://www.thecrazyprogrammer.com/2017/03/why-array-indexing-starts-with-0-in-c.html

数组如何定义索引开头

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值