Why Arrays start at 0 instead of 1 [duplicate]

13

Why arrays start at 0 instead of 1?

There are not 0 people, 0 animals, 0 nothing ... (do not cling to this part)

What is the purpose of doing this? I think it's not just me who does not understand the logic of it, if at all.

    
asked by anonymous 12.02.2018 / 00:41

3 answers

19

An array is a set of elements arranged side-by-side in memory from an address.

For example, let's say in memory you have 10 integers in an array. And that the address of this array in memory is 100 (this number is chosen by the OS, which found a free memory area for the array).

As each integer has 4 bytes, the first element will be in the index itself 100, the second in index 104, the third in index 108, and so on.

How to calculate the element's memory position in a generic way? See:

Primeiro elemento: 0 * 4 bytes + 100 bytes
Segundo elemento: 1 * 4 bytes + 100 bytes
Terceiro elemento: 2 * 4 bytes + 100 bytes.
Looking at the calculations, it is easy to see why it was agreed that the index would be based on 0, not on 1. Thus, it would not be necessary to subtract 1 if such a calculation had to be made (and in the first languages, it was very common that such calculations were made, since much memory was manipulated in the hand). And even for a compiler, it would be easier to do the conversion.

Another reason is that in mathematics (and early applications were very mathematical) it is very common to use elements based on 0.

Note that this is just a convention. There is no technical reason in terms of memory performance or expense that justifies it. Some older compilers had indexes based on 1, or even configurable ones (as is the case with Pascal, language prior to C). There is no bit loss or performance because the compiler is able to subtract this index at compile time, but using an index based on 0 was very practical and this convention holds to this day.

    
12.02.2018 / 00:46
1

This response should be a comment. An answer in English for your question can be found at: link

My comment is that you are confusing the zero ordinal number (in linguistics) with the zero cardinal number. The index of an array does not designate an amount (not a cardinal number), but a position in a sequence. In everyday life, it is more common to index an ordering beginning with the 'first' element, followed by the 'second' and so on. But since both cardinal and ordinal numbers generalize natural numbers, they both include zero, and it is perfectly possible to index an order starting with "zero" or "zero"

    

14.02.2018 / 23:17
-4

Simply because the decimal numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9, not 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10 as we commonly count (erroneously).

    
12.02.2018 / 05:21