What’s up with zero-based arrays?

From the series "What the heck were they thinking":
 
Every now and then I find myself wondering about some things that just don’t make sense on the software development world. I’ll start blogging about that type of thing just so that I can keep track of those things.
 
One thing that is just way over my ahead to understand is a zero-based array. Come on, people, I’m not smart enough to understand that: MyArray[0] is the first element… MyArray[1], the second… No, seriously, what’s up with that? It’s just not intuitive at all. It’s like saying "on my first birthday I’ll be two years old". Or that "my second marriage is my marriage number 1".
 
How many times have people messed up a for loop because they forgot about the darn zero-based array?
 
"Pseudo code"
For i = 1 to Array.Lenght
    var = Array[i-1]
 
Gimme a break. That’s just wrong. You go explain this to somebody who’s not into programming, he/she is going to say: "hmmm… that doesn’t look like something created by somebody really smart, who’s supposed to know something about logic… that’s just the opposite of logic".  🙂
  1. #1 by Unknown on August 13, 2005 - 9:14 am

    Actually, zero-based arrays are perfectly natural from the machine\’s point of view. An array is simply a contiguous sequence of bytes in memory. The memory address of any given element of an array can be calculated from its element number, the starting address of the array, and the length of each entry. The offset from the starting address of the array to the start of the nth element is ( length * ( n – 1)). The first element of an array therefore has an offset of zero, which is why zero-based arrays are natural. It actually takes some manipulation behind the scenes to implement the more intuitive one-based array in a programming language.

  2. #2 by Claudio on August 13, 2005 - 3:47 pm

    Hi Rick,I was pretty sure somebody would come by with an explanation for that non-sense. You academic people. :)If we were to see things from the perspective of what\’s natural for the machine, then we should drop everything and just type 1s and 0s, right? No need for fancy programming languages or IDEs. 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: