Why always array starts with index 0

Showing Answers 1 - 3 of 3 Answers

Here is my interpretation, let me know whether its convincing or not: For this, one must understand what happens internally when you create an array. When you create an array, say something like this: int a[5];5 continuous memory locations are allocated for this array. Now, 'a' is nothing but a constant pointer that points to the first location of that continuous memory. To elaborate this with an example, lets do the following:int a[5] = {10,20,30,40,50};lets assume that 5 contigious memory locations created for this are 1000,1001,1002,1003,10041000 has the value 101001 has the value 201002 has the value 301003 has the value 401004 has the value 50'a' is a constant pointer to the location 1000. So, if you do cout<

paulson paul chambakottukudyil

  • Apr 12th, 2006
 

Array name is a constant pointer pointing to the base address(address of the first byte where the array begin) of the memory allocated. When you use arr[i], the compiler manipulates it as *(arr + i). Since arr is the address of the first element, the value of i must be 0 for accessing it. Hence all arrays begin with an index of 0.

  Was this answer useful?  Yes

MOHIT GONDULEY

  • Apr 20th, 2006
 

In case of Array , the ArrayName is Nothing but a Base Address, when we use [] operator , it treats leftmost
value as a base address and rightside value as an offset so it adds BaseAddress+Offset and get target address
where actually value is stored , BaseAddress+Offset = Target Address (Where the desire value is stored).

Hoping this will clear you the internal work of Compiler ,For more clearing your view see following Example.
You can write me on mohit.gonduley@gmail.com to convey your valuable views

************************************************************************************
#include "stdio.h"
#include "stdlib.h"

int main(void)
{
 int iArr[2] = {10,20};
 printf("\n*** PRINT 1ST  ELEMENT IN TRADITIONAL WAY :- %d    \n",iArr[0]);
 printf("\n*** PRINT 1ST  ELEMENT IN UNUSUAL WAY :- %d    \n",0[iArr]);
 printf("\n*** PRINT 1ST  ELEMENT IN UNUSUAL WAY :- %d    \n",*(0+iArr));
 return 0;
}
************************************************************************************

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions