Arrays and Memory in C
For Complete YouTube Video: Click Here
In this class, we will try to understand the Arrays and Memory in C.
The concepts of an array and array initialization have been discussed in our previous classes.
Table of Contents
Arrays and Memory
The image below is the programming example for the illustration of arrays and memory.
In the above example, we have declared an array with three elements 4, 6, and 9.
The image below is the visualization of an array that we had so far in our previous classes.
Now we will try to understand how an array of elements will get stored on the memory.
In the above example, an array of integers have been declared.
Let us assume that an integer occupies four bytes of space, and the first byte of the first element of the array is stored at memory location 50 as shown in the image below.
From 50 to 54, the first element four will get stored from 55 to 58, the second element six will get stored, and from 59 to 62, the third element nine will get stored.
The clear visualization of the memory is shown in the image below.
Accessing the elements of an array
To access the elements of an array, we use index methods like a[1], a[2] etc.
From the above image, whenever a[1] is identified, the compiler will access the bits from memory location 55 and for a[2], the bits from 59 will be accessed.
How will the compiler calculate the address?
It is based on the formula given below.
Base address + size of the element * index.
For example, a[1] is used in printf(“%d”, a[1]);.
Address = 50 + 4 * 1.