C++ 为什么数组索引从'0'开始

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16892862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:44:25  来源:igfitidea点击:

Why Array index start from '0'

c++carrays

提问by Vivek Sadh

I have a question on C/C++ arrays.

我有一个关于 C/C++ 数组的问题。

Why does the index of the arrays start from '0' not from '1'?

为什么数组的索引从“0”而不是“1”开始?

Is there any mathematical reason for that?

有什么数学原因吗?

回答by Vivek Sadh

In most programming language, the name of any array is a pointer, which is nothing but a reference to a memory location, and so the expression array[n] points to a memory location which is n-elements away from the first element. This means that the index is used as an offset. The first element of the array is exactly contained in the memory location that array points to (0 elements away), so it should always be referred as array[0].

在大多数编程语言中,任何数组的名称都是一个指针,它只不过是对内存位置的引用,因此表达式 array[n] 指向距离第一个元素有 n 个元素的内存位置。这意味着索引用作偏移量。数组的第一个元素正好包含在数组指向的内存位置(0 个元素之外),所以它应该总是被称为数组 [0]。

a[i] can also be read as value at [a+i] which is denoted as *(a+i) , so it always starts at zero.

a[i] 也可以读作 [a+i] 处的值,表示为 *(a+i) ,所以它总是从零开始。