Pointersand Array
Pointersand Array
In this tutorial, we will learn about the relation between arrays and pointers
with the help of examples.
In C++, Pointers are variables that hold addresses of other variables. Not only
can a pointer store the address of a single variable, it can also store the
address of cells of an array.
Consider this example:
int *ptr;
int arr[5];
Here, ptr is a pointer variable while arr is an int array. The code ptr =
arr; stores the address of the first element of the array in variable ptr .
Notice that we have used arr instead of &arr[0] . This is because both are the
same. So, the code below is the same as the code above.
int *ptr;
int arr[5];
ptr = &arr[0];
The addresses for the rest of the array elements are given
by &arr[1] , &arr[2] , &arr[3] , and &arr[4] .
Point to Every Array Elements
Suppose we need to point to the fourth element of the array using the same
pointer ptr .
Here, if ptr points to the first element in the above example then ptr + 3 will
point to the fourth element. For example,
int *ptr;
int arr[5];
ptr = arr;
Similarly, we can access the elements using the single pointer. For example,
#include <iostream>
using namespace std;
int main()
{
float arr[3];
// ptr = &arr[0]
ptr = arr;
return 0;
}
Run Code
Output
In the above program, we first simply printed the addresses of the array
elements without using the pointer variable ptr .
Then, we used the pointer ptr to point to the address of a[0] , ptr + 1 to point
to the address of a[1] , and so on.
In most contexts, array names decay to pointers. In simple words, array
names are converted to pointers. That's the reason why we can use pointers
to access elements of arrays.
However, we should remember that pointers and arrays are not the same.
There are a few cases where array names don't decay to pointers. To learn
more, visit: When does array name doesn't decay into a pointer?
#include <iostream>
using namespace std;
int main() {
float arr[5];
return 0;
}
Run Code
Output
Here,
1. We first used the pointer notation to store the numbers entered by the user
into the array arr .
Notice that we haven't declared a separate pointer variable, but rather we are
using the array name arr for the pointer notation.
As we already know, the array name arr points to the first element of the
array. So, we can think of arr as acting like a pointer.
2. Similarly, we then used for loop to display the values of arr using pointer
notation.