Program Demonstrating Contiguous Memory Allocation in Arrays
Contiguous memory allocation is a fundamental concept in computer programming, particularly when working with arrays. Understanding how arrays store elements in continuous memory locations is crucial for efficient memory access and manipulation. In this article, we will explore a program that demonstrates contiguous memory allocation in arrays using the C++ programming language. By examining this program, we will gain insights into how arrays are stored in memory and how their contiguous nature benefits data access and processing. So let’s dive in and uncover the fascinating world of contiguous memory allocation in arrays through this enlightening program.
#include <iostream> using namespace std; int main() { int arr[5]; // Declare an array of size 5 // Output the memory addresses of array elements for (int i = 0; i < 5; i++) { cout << "Address of arr[" << i << "]: " << &arr[i] << endl; } return 0; }
In this program, we declare an integer array arr
of size 5. We then use a loop to output the memory addresses of each array element using the &
operator. By printing the memory addresses, we can observe whether the elements are stored in contiguous memory locations.
When you run the program, you should see the memory addresses printed out sequentially, indicating that the array elements are indeed stored in contiguous memory allocation.
Output:
Address of myArray[0]: 0x7ffeefbff540 Address of myArray[1]: 0x7ffeefbff544 Address of myArray[2]: 0x7ffeefbff548 Address of myArray[3]: 0x7ffeefbff54c Address of myArray[4]: 0x7ffeefbff550
Note that the actual memory addresses may vary each time you run the program, but the key observation is that the addresses are incremented by the size of the array’s data type (in this case, int , 4 bytes at 64-bits compiler).
This demonstrates how arrays in C++ are stored in contiguous memory allocation, ensuring efficient memory access and element traversal.