[Tutor] 'Common' mistake ... for other newbies
jb
jb at riseup.net
Mon Apr 12 18:51:09 EDT 2004
On Mon, Apr 12, 2004 at 11:36:32PM +0200, denis wrote:
>
> Well,
>
> Thank you David for this clear message.
> Are they here people who think that such a so-called "mistake" is not a
> mistake ? That David programmed the way he (and we, humans should ; and
> that the error lies in language, not in his brain ? Why are indexes based on
> 0 instead of 1 ?
most computer people come from the C programming language, and indexes
start from 0 in C, so this is what many people are used to.
it's my understanding that indexes start from 0 in C to simplify pointer
arithmetics:
in C, when you want to use an array, you need to allocate a block of
memory to store it:
here I use an array a with room for 3 integers: I have to allocate it with
the following incantation: "a = (int*) malloc(3*sizeof(int))" - the value
that will be stored in "a" is the address of the first cell of the array
in memory.
a a+1 a+2 <- addresses in memory
__________________
| | | |
| 5 | 4 | 3 | <- values stored in my array
|_____|_____|_____|
if you want consistency between the place of something in the array and
its place in memory (i.e. its address in memory), the simplest thing is
to use the convention that indexes start at 0, so that you can write
horrors like *a (same as a[0]), *(a+1) (same as a[1]), etc.
some languages (FORTRAN and probably others) have indexes that start
from 1, but they have no pointers.
also, counting from 0 or from 1 really depends on the person. When I
was at school, i had no fun putting variables i had called x0, x1 in
arrays indexed from 1 (in FORTRAN, of course.), and at that time, I
had not been brainwashed by programming languages :)
i hope this helps.
jb
More information about the Tutor
mailing list