Pointers and Arrays

Pointers and Arrays

Relationship between Pointers and Arrays and how to use them

Nov 18, 20173 min read

Overview:

You already know how to use pointers by performing arithmetic operations on them but you’re still confused about when and why you would use these techniques? Follow along this tutorial to clear your confusion and learn how to use pointers with arrays.

Relationship between Pointers and Arrays:

What’s interesting about the relationship between pointers and arrays, is that if we assign an array to a pointer, the pointer variable virtually becomes the array.

What do you mean it becomes the array?

To answer your question, we have to look at another fun example:

Fun example:

#include <iostream> using namespace std; const int LENGTH = 3; int main() { int numbers[LENGTH]; int * ptr = numbers; ptr[0] = 10; numbers[1] = 20; *(ptr + 2) = 30; for(int i = 0; i < LENGTH; i++) { cout << numbers[i] << "\n"; } return 0; }

Let’s discuss the most important lines in the above code block.

int numbers[LENGTH];

To start, we are simply declaring an array called numbers with a fixed LENGTH.

int * ptr = numbers;

This is the interesting part. Here, we are declaring a new pointer ptr which is being assigned the numbers array. Technically, ptr now holds the address of the first element of numbers array. Referring back to your question, the pointer virtually becomes the array because we can now use the pointer variable ptr as we would use the numbers array. In other words, we can access elements in the numbers array using the pointer variable ptr in conjunction with pointer arithmetics and/or array-style indexing. Lines 8, 9 and 10 use each of the various ways to access the elements in the numbers array.

ptr[0] = 10;

In this line of code, the pointer variable ptr is using array style indexing to set the first value of the numbers array to 10.

numbers[1] = 20;

To show that we can still use the numbers variable, we are setting the second element of the numbers array using the good ol' array indexing with the numbers variable itself.

*(ptr + 2) = 30;

This is a simple example of how to use pointer arithmetics on pointers to access values beyond the address assigned to the pointer. This particular line of code adds the current size of the type of the pointer, which in this case is an integer, to ptr and the dereference operator helps us change the third element in the array.

Executing the last part of the code gives us the following result:

10 20 30

You now have a basic idea of how to use pointers and arrays together.

In a nutshell:

Pointers are not arrays, however, if you assign an array to a pointer, the pointer virtually becomes the array. The pointer will contain the address of the first element of the array and it can read and write each element of the array by using pointer arithmetics and/or array-style indexing.