How exactly does indexing works in Arrays?

First, let’s understand arrays, It is a collection of items stored at contiguous memory locations. The basic idea is to store multiple items of the same type together which can be accessed by index/key (a number).

The contiguous memory of declared size is allocated on heap/stack and then the address of the element is calculated mathematically during run-time as:-

element address = (base address) + (element index * size of a single element)

where,

  • Base address: It is the address of the element at the index 0 or the location of the first element of the array in the memory.. The compiler knows this address as the memory location of the array.
  • Element index: It is the sequential number (index/key) assigned to the element where the first element of the array is assigned 0. It can also be defined as the number of elements prior to that particular element in the array.
  • Size of a single element: Elements in the array need to be of the same data type or object. The size of the single element is the number of bytes required in memory to store a single element of that kind.

For example:

Int type requires 4-bytes (32-bit)
char type requires a 1-byte (8-bit)
long type requires 8-byte (64-bit) etc.

Example of above implementation:

int arr[6] = {3, 4, 7, 9, 7, 1}
address of arr[0] (base address) = 0 x 61fe00 
address of arr[3] (element address) = (base address) + (element index * size of a single element)
0 x 61fe00 + ( 3 * 4) = 0 x 61fe0c
Here, size of a single element is 4-bytes as it is int- type array.

long long arr[6]={100, 12, 123, 899,124, 849}
address of arr[0] (base address) = 0x61fdf0
address of arr[3] (element address) = (base address) + (element index * size of a single element)
0x61fdf0 + ( 3 * 8) = 0x61fe08
Here, size of a single element is 8-bytes as it is long – type array.

Note: Here addresses are of Hexadecimal form.

Let’s see its implementation through a program to print the address of the array elements:

C++

#include <iostream>

  

using namespace std;

  

int main() {

    int arr[6] = {3,4,7,9,7,1};

    cout << "Base address:- " << (&arr) << endl;

    cout << "Element address at index 3:- " << (&arr[3]) << endl;

    return 0;

}

Output

Base address:- 0x7ffc64918c30
Element address at index 3:- 0x7ffc64918c3c