Memory Representation of One Dimensional Array in C
Memory for an array is allocated in a contiguous manner i.e. all the elements are stored adjacent to its previous and next eleemtn in the memory. It means that, if the address of the first element and the type of the array is known, the address of any subsequent element can be calculated arithmetically.
The address of the ith element will be calculated as given the base address (base) and element size (size):
Address of ith element = base + (i x size)
This structured memory layout makes accessing array elements efficient.
Note: The name of the array is the pointer to its first element. And also, we don’t need to multipy the size of the data type. The compiler already do it for you.
Example: To Demonstrate the 1D Array Memory Layout
// C++ program to illustrate the memory layout of one
// dimensional array
#include <stdio.h>
int main()
{
// declaring array
int arr[5] = { 11, 22, 33, 44, 55 };
// pointer to the first element of the array;
int* base = &arr[0];
// size of each element
int size = sizeof(arr[0]);
// accessing element at index 2
printf("arr[2]: %d\n*(base + 2): %d\n", arr[2],
*(base + 2));
printf("Address of arr[2]: %p\n", &arr[2]);
printf("Address of base + 2: %p", base + 2);
return 0;
}
Output
arr[2]: 33 *(base + 2): 33 Address of arr[2]: 0x7fff1841c3c8 Address of base + 2: 0x7fff1841c3c8
As we can see, the arr[2] and (base + 2) are essentially the same.
One Dimensional Arrays in C
In C, an array is a collection of elements of the same type stored in contiguous memory locations. This organization allows efficient access to elements using their index. Arrays can also be of different types depending upon the direction/dimension they can store the elements. It can be 1D, 2D, 3D, and more. We generally use only one-dimensional, two-dimensional, and three-dimensional arrays.
In this article, we will learn all about one-dimensional (1D) arrays in C, and see how to use them in our C program.