C++ Pointers and Arrays
C++ Pointers and Arrays
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] .
int *ptr;
int arr[5];
ptr = arr;
Similarly, we can access the elements using the single pointer. For example,
// use dereference operator
*ptr == arr[0];
*(ptr + 1) is equivalent to arr[1];
*(ptr + 2) is equivalent to arr[2];
*(ptr + 3) is equivalent to arr[3];
*(ptr + 4) is equivalent to arr[4];
#include <iostream>
using namespace std;
int main()
{
float arr[3];
// declare pointer variable
float *ptr;
// 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.
#include <iostream>
using namespace std;
int main() {
float arr[5];
return 0;
}
Run Code
Output