C++ Program to Access Elements of an Array Using Pointer
A Pointer is a variable that stores the memory location or address of an object or variable. In other words, pointers reference a memory location, and obtaining the value stored at that memory location is known as dereferencing the pointer.
An Array is the collection of homogeneous elements stored in contiguous memory blocks. So, elements in an array can be accessed using a pointer.
Access elements using Pointer
Pointer has the capability to store the address, So, we can store the address of the first element of the array and then traverse the pointer till we reach the end element.
Methods to store the address of the first elements of the array are mentioned below:
- int *ptr = arr;
- int *ptr = &arr;
After this, a for loop is used to dereference the pointer and print all the elements and the memory location of the element of the array. At each loop iteration, the pointer points to the next element of the array. Then the array value and address are printed. Let’s check the Pointer to array example.
Value of0 arr is 6 Address of 6 is 0x7ffc9de51fb0 Value of1 arr is 2 Address of 2 is 0x7ffc9de51fb4 Value of2 arr is 5 Address of 5 is 0x7ffc9de51fb8 Value of3 arr is 7 Address of 7 is 0x7ffc9de51fbc Value of4 arr is 4 Address of 4 is 0x7ffc9de51fc0
Please Login to comment...