Arrays form the core data structure in computer science. Their role is to help store and
manipulate large numbers of data values. This chapter explains how arrays are stored in
memory and how this understanding can be used to improve the performance of our
programs.
Memory Representation
The first step toward comprehension of how arrays are stored in memory is to understand
the basic operations of memory itself. Memory consists of a vast array of bytes, each
uniquely addressed. When any variable is declared, the operating system reserves a given
block of memory for the variable and maintains the address of the location in a register.
For instance, let us take the declaration of the integer variable x and its initial assignment as
5.
int x = 5;
This could store the address of 0x1000 in variable x but keep value 5 at that particular
address.
Arrays
An array is defined to be a set of variables that have the same data type, aligned in memory
and located in contiguous memory addresses. Thereby, when a programmer declares an
array of integers using the syntax int arr[10], the operating system assigns a sufficient
segment of memory for ten integers so that each integer will occupy successive memory
locations.
For instance, say an integer array is declared: int arr[10] = {1, 2, 3, 4, 5}. The OS might assign
the address 0x2000 to store the address of arr and write the corresponding values in the
following way:
Number | Value | \n--- | --- | \n0x2000 | 1 | \n0x2001 | 2 | \n0x2002 | 3 | \n0x2003 | 4
| \n0x2004 | 5 |
The elements of an array may be referenced using indices, which are integers, starting at
zero, increasing by one for every successive element. So the first element of an array is
accessed by arr[0], the second by arr[1], and so on.
Accessing Arrays Accessing elements from an array is one of the most common operations in
programming, yet also one of the slowest if not done very carefully, as access to elements
involves reading from and writing to physical locations within the memory that is used by a
computer.
In other words, there is an alternative method of improving the access efficiency of the array
called blocking, that is, partitioning of an array into blocks or segments and then accessing
these segments sequentially. This ensures less number of memory accesses.