Why does indexing in arrays start from zero?

Prehistory: the idea to write this article appeared after the exam on programming and algorithmization, during which I proved to the teacher for about an hour that the program written by me works correctly.

The task was the simplest one, in which I needed to perform certain operations with the element number n (read n from the standard input thread). And the teacher, setting n = 100, for example, saw that the 99th element was changing…

Let’s get to the point.
图片[1]-Why does indexing in arrays start from zero? - 拾光赋-拾光赋
Why do we count from zero, and not from one, because it would be easier for everyone?

The point is that the array index is the shift of an element address in memory by an average number of bits relative to the beginning of the array (the first element) calculated by the formula n * size where n is the element index, size is the number of bits occupied by one array element (it depends on the data type).

For example, if we have an array numbers[] that contains elements of an integer data type (int) that occupy 4 bytes each, i.e. 32 bits (more details below), the shift of an element with index 5 (numbers[5]) relative to the beginning of the array will be 5 * 4 bytes = 20 bytes = 160 bits.

Here we can conclude that the first element in the array is the one with index 0, since we will get the numbers[] array above by the example: 0 * 4 bytes = 0 bytes = 0 bits. The shift relative to the beginning of the array is 0 bits, which means that the element numbers[0] is the first element.

We can also make sure that the numbers[1] element is not the first element, as it is shifted from the beginning of the array by 8 bits.

So don’t confuse and ask people around you not to confuse “element with number 3” and “third element”.

More about 32 bits occupied by the int type. The number of bits allocated by modern compilers for int type data on 32-bit systems and processors is given. On 16-bit platforms 2 bytes are most often allocated, that is 16 bits.

Hope the article was useful.

原文链接:Why does indexing in arrays start from zero?

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容