Pointers are the variables that store the memory address of another variable. Pointers are used in an array to store the address of the first cell of the array.
int x=10; // ptr is a pointer storing the address of variable x int *ptr=&x;
‘&’ operator is used with variable x to return the address of x to ptr
int *ptr; int arr[5]; ptr=arr;
ptr is the pointer referencing to the first index of the array. Since Array is iterative in nature and elements are stored in a contiguous memory location. So, there is no need to store the address of all other elements separately.
We can replace arr with &arr[0] (i.e. Address of the first element of the array )
int *ptr; int arr[5]; ptr=&arr[0];
Similarly , for accessing the memory address of other variables of array , we can use &arr[1] , &arr[2], &arr[3] and &arr[4].
Using Dereference operator
int* ptr=arr[0]; *(ptr+1) ⇶ arr[1] *(ptr+2) ⇶ arr[2] *(ptr+3) ⇶ arr[3] *(ptr+4) ⇶ arr[4]
Note – ptr + 1 does not mean that we are shifting 1 byte ahead. It actually means that if we are using an integer type array since the int data type occupies 4 bytes. So, ptr+1 signifies that we are shifting 4 bytes ahead. Similarly, for other data types as well.
Displaying the address of all array elements using array and pointers
Code:
C++ Code
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Initialising Array
int arr[5];
// Declaring pointer
int *ptr;
cout<<"Using array for printing the address of array elements"<<endl;
for (int i = 0; i < 5; i++)
{
cout << "&arr[" << i << "] = " << &arr[i] << endl;
}
ptr = arr; // or &arr[0] -> address of first element of array
cout<<"Using pointers for printing the address of array elements"<<endl;
for (int i = 0; i < 5; ++i)
{
cout << "ptr + " << i << " = "<< ptr + i << endl;
}
return 0;
}
Output:
Array name used as a pointer
Code:
C++ Code
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[5]={4,5,6,7,8};
// Array name used a pointer
cout << "Array Elements are: " << endl;
for (int i = 0; i < 5; ++i)
{
cout << *(arr + i) << endl ;
}
return 0;
}
Output:
Special thanks to Gurmeet Singh for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article