Analyse Array Element Addresses

Array Element Addresses

Create a simple program that declares an array of integers, prints the values of its elements, and prints the memory addresses of its elements using the & operator. Analyze how the addresses are spaced.

Hint

Use &array[i] to get the address of an element.

Answer

#include <iostream>

int main() {
    const int size = 5;
    int arr[size] = { 10, 20, 30, 40, 50 };

    std::cout << "Values of the array elements:" << std::endl;
    for (int i = 0; i < size; ++i) {
        std::cout << "arr[" << i << "] = " << arr[i] << std::endl;
    }

    std::cout << "\nMemory addresses of the array elements:" << std::endl;
    for (int i = 0; i < size; ++i) {
        std::cout << "Address of arr[" << i << "] = " << &arr[i] << std::endl;
    }
}

The output will vary depending on where arr was allocated. However, it should look something like this:

Values of the array elements:
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50

Memory addresses of the array elements:
Address of arr[0] = 000000385173FB80
Address of arr[1] = 000000385173FB84
Address of arr[2] = 000000385173FB88
Address of arr[3] = 000000385173FB8C
Address of arr[4] = 000000385173FB90

The address is given in hexadecimals (base 16 counting). We won't cover this number system here. The important thing to note is the even spacing between each array element. In this example; the first element of the array is placed at ...FB80. The second is placed at ...FB84 (4 bytes higher). Each following element is placed 4 bytes after the last element. This is because it takes 4 bytes to store an int. Changing the type of arr to double [] would make the elements be placed 8 bytes appart, as that's how many bytes a double uses.

Questions