by BehindJava

# How arrays are stored in the memory

Home » datastructures » How arrays are stored in the memory

In this tutorial, we are going to see how the array are stored in the memory.

# Arrays Internal Working

• Arrays are stored via contiguous blocks in memory.
• Every element occupies the same amount of space in memory.
• If an array starts at memory address x, and the size of each element in the array is y. we can calculate the memory address of the ith element by using the following expression i.e., x + i * y
• If you know the index of an element, the time to retrieve the element will be the same no matter where it is present in the array.

Start address of array = 12, element size = 4 bytes

Address of array[0] = 12
Address of array[1] = 12 + (1 * 4) = 16
Address of array[2] = 12 + (2 * 4) = 20
Address of array[3] = 12 + (3 * 4) = 24
Address of array[4] = 12 + (4 * 4) = 28
Address of array[5] = 12 + (5 * 4) = 32
Address of array[6] = 12 + (6 * 4) = 36

Now, for this example, we’re gonna pretend the start address of the array is 12 which is a bogus memory address and element size is four bytes.

• If we want to get the element at array zero, well that’s equal to the start address of the array because the array starts here at 12. So the first element of the array is actually going to have the same address as the beginning of the array.
• To access the second element i.e., 35. we add four bytes to start of array which is 12, and now we’re at the start address for the 35.
• So, one of the things that arrays are really good at doing is retrieving elements if you know the index.