Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First element in array

Why do indexes in arrays always start with 0? Does it have something to do with binary? For example:

var myArray = [5,6,7,8];

To access the number 5, you would have to say

myArray[0]

But why?

No, I don't have a real problem. As you can evidently tell I'm new to this stuff.

like image 265
Ptr13 Avatar asked Nov 29 '25 17:11

Ptr13


2 Answers

I'm sure this has been asked an answered a hundred times, but I'll bite.

One way of looking at the "index" or "key" is as an "offset".

myArray essentially acts as a pointer to the first item in a series of items. Specifically, it points to the number "5" in memory. So when you say myArray[1] it's like saying "the location of the first element in myArray plus 1 item over", thus you would be jumping over the first element.

In C, when you write *myArray (pointer dereference) it actually gives you back the first element.

#include <stdio.h>

int main(void) {
    int myArray[] = {5,6,7,8};
    printf("%d",*myArray); // prints "5", equivalent to myArray[0]
    printf("%d",*(myArray+1)); // prints "6", equivalent to myArray[1]
    return 0;
}

There are more practical reasons than "that's the way computers work" too.

like image 149
mpen Avatar answered Dec 01 '25 07:12

mpen


nice blog about the historical reasons: http://developeronline.blogspot.fi/2008/04/why-array-index-should-start-from-0.html

like image 40
ahaaman Avatar answered Dec 01 '25 07:12

ahaaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!