Prerequisite : Pointers in C/C++
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.
#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; } |
2 2
The conclusion is, we need random access in array. To provide random access, compilers use pointer arithmetic to reach i-th element.
Recommended Posts:
- Rearrange array such that even index elements are smaller and odd index elements are greater
- Longest alternating sub-array starting from every index in a Binary Array
- Construct an array from XOR of all elements of array except element at same index
- Sum of the elements from index L to R in an array when arr[i] = i * (-1)^i
- Equilibrium index of an array
- Find the index of first 1 in a sorted array of 0's and 1's
- Sort the array in a given index range
- Find the index of first 1 in an infinite sorted array of 0s and 1s
- Array Index with same count of even or odd numbers on both sides
- Delete array element in given index range [L - R]
- Overloading Subscript or array index operator [] in C++
- Find index of first occurrence when an unsorted array is sorted
- Find a Fixed Point (Value equal to index) in a given array
- Index with Minimum sum of prefix and suffix sums in an Array
- Count of index pairs with equal elements in an array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



