1

Not really a code problem but a doubt, why do arrays on C and C++ start on 0? Does it have anything to do with some internal process?

int array[4]={1,2,3,4};
cout<<array[0];
cout<<array[1];
cout<<array[2];
cout<<array[3]; ///This prints 1234

But why that instead of

int array[4]={1,2,3,4};
cout<<array[1]; //as the first element
cout<<array[2];
cout<<array[3];
cout<<array[4]; 

?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 1
    Similar to https://stackoverflow.com/questions/7320686/why-does-the-indexing-start-with-zero-in-c – Dr G. Apr 23 '19 at 05:01
  • Have a look at https://en.m.wikipedia.org/wiki/Zero-based_numbering – kvantour Apr 23 '19 at 05:03
  • It's syntactic sugar. 'array' is this context is effectively just a memory address. The first element is therefore (array + 0), or array[0]. The second is (array + 1), etc, etc. – robthebloke Apr 23 '19 at 06:17

2 Answers2

4

Because the notation does pointer arithmetic. array[0] actually means the location of the array plus the size of 0 elements.

As always in C, you're working close to the hardware.

ravnsgaard
  • 922
  • 1
  • 10
  • 20
0

Consider int arr[i] elements.

arr[i] is interpreted as *(arr + i). Now, arr is the address of the array or address of the 0th index element of the array. So, address of next element in the array is arr + 1 (because elements in the array are stored in consecutive memory locations). So if you do *(arr+0) it gives the starting memory location of the array. and *(arr+1) gives next memory location. so this i i.e 0,1,..etc can use like offset.

As @ravnsgaard said in C, you're working close to the hardware.

Rohit Suthar
  • 967
  • 9
  • 22