Answer

  • This means that the index is used as an offset. The first element of the array is exactly contained in the memory location that array refers (0 elements away), so it should be denoted as array[0] . Most programming languages have been designed this way, so indexing from 0 is pretty much inherent to the language.

    Answered By:
    arvin
  • This means that the index is used as an offset. The first element of the array is exactly contained in the memory location that array refers (0 elements away), so it should be denoted as array[0] . Most programming languages have been designed this way, so indexing from 0 is pretty much inherent to the language.

    Answered By:
    arvin
  • Consider int arr[100]. The answer lies in the fact how the compiler interprets arr[i] ( 0<=i<100).
    arr[i] is interpreted as *(arr + i). Now, arr is the address of array or address of 0th index element of array. So, address of next element in array is arr + 1 (because elements in array are stored in consecutive memory locations), further address of next location is arr + 2 and so on . Going with above arguments, arr + i means address at i distance away from starting element of array. Therefore, going by this definition, i will be zero for starting element of array because starting element is at 0 distance away from starting element of array. To fit this definition of arr[i], indexing of array starts from 0.

     

    filter_none

    edit

    play_arrow

    brightness_4

    #include<iostream>
    using namespace std;
      
    int main()
    {
        int arr[] = {1, 2, 3, 4};
      
        // Below two statements mean same thing
        cout << *(arr + 1) << " ";
        cout << arr[1] << " ";
      
        return 0; 
    }

     

    Output:
    2 2
    

     

    The conclusion is, we need random access in array. To provide random access, compilers use pointer arithmetic to reach i-th element.


             

    Answered By:
    arvin

686

Questions

Ask Question