why arrays first index starts with 0
Because index actually means the offset from the pointer. The offset of the first element is 0.
Update upon comment Well, I'll try.
Let's consider an array of bytes with 10 elements:
byte array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Consider the memory cells where this array is located (lets assume it starts from the address 0010h):
0010 0011 0012 0013 0014 0015 0016 0017 0018 0019
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
Our variable array
points to 0010h
.
The offset of 1
(the first element) is 0
and its actual address is 0010 + 0
(where 0010
is the address of array
and 0
is the offset).
The offset of 3
(the third element) is 2
because it is in the third cell, and the cell size is 1
(because we have byte array). the 3rd element's actual address is 0010 + 2
.
Coming back to our programming language: array[0]
means the content of the memory cell which has the 0010
address, array[1]
means the content of the memory cell with the 0010 + 1
address (the second element) and so on. *array
in C refers to the first element, *(array+1)
- to the second.
The same reason that mathematically-minded people call tomorrow "one day from now" rather than "two days from now".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With