C/Why array index starts at 0?
Expert: Prince M. Premnath - 9/6/2010
QuestionWhy array index starts with zero?
AnswerHi Dear Snehal ,
My apologies for the delayed response :( .. well getting to the point
if we say a[0]; /* Means the first element of the array */
as you know well 'a' is the array name ( which holds the base address of the array ) say if the array starts in the memory location addressed 2000 then the value of 'a' ( Array name ) is 2000 ( you can ensure this by just printing the value of a ) the index value what you give inside the square bracket is also referred as offset (means the number of positions to be moved from the base address , this offsetting technique will vary based on the array type , say int , float , char ..)
if its an integer array pointer increment will be counted 2 ( since its two bytes of length , 4 for float and so on ).
so with the case of every integer pointer increment the address value will be incremented by two
for eg a[0] will be at the address 2000
a[1] will be at the address 2002 and so on
how come ?
The complier treats a[0] as *(a+0) ie *(a+0) (array name is
the base address of that array)gives the first element of
the array.
If the array starts from 1 a[1] is treated as *(a+1) gives
the second element of array.The first element is missing.so
array always starts from 0.
Hope this will help you out understanding little.
please get back to me if you require additional support
Thanks and Regards
Prince M. Premnath