Fusion of Engineering, Control, Coding, Machine Learning, and Science

Connection Between Arrays and Pointers in C++ – C++ Tutorial

In this tutorial, we explain a very important connection between arrays and pointers in C++. The YouTube tutorial accompanying this webpage tutorial is given below.

Important Connection Between Array Variables and Pointer Variables in C++ -  Tutorial

Before we explain the connection between arrays and pointers, we first need to explain:

  1. How variables are stored in the computer memory.
  2. How arrays are stored in the computer memory

How variables are stored in the computer memory

The figure below is a sketch of the computer memory with bytes and addressed. The bytes are rectangular slots. Next to every byte, we have its address that is used to access that particular byte.

These points are illustrated in the figure below.

Since both “a” and “b” are integers they occupy 4 bytes each in the memory space. These bytes are consecutive for every variable and they are represented by the shaded regions.

How array variables are stored in the memory

This is illustrated in the figure below

To access or modify any variable in the array, the compiler needs to know only the address of the first byte of a[0] and the data type of the stored variable. Then, it will simply offset the address of the first byte of a[0] to access any other variable. For example, to access a[1], the address of a[0] has to be offset by 4 in the figure above.

Arrays and pointers

Now we are ready to explain the connection between arrays and pointers. Let us decleare an array a:

int a[3]

To conclude, array names are actually pointers. Newly defined pointers can be used to point to the names of the variables of arrays, and we can use these new pointers and the operator [] to access the variables stored in the array. The code below explains this and gives an example on how to use pointers and arrays:

// Program that demonstrates that array names are pointers

// The array name is a constant pointer that points to the first indexed variable of the array

#include<iostream>
using namespace std;

int main()
{
// let us declare an array
int a[10];
// pointer to integer
int *p;
for (int index=0; index<10; index++)
{
    a[index]=index;
}
// now p points to the same memory location that a points to
p=a;
// print now the entries of the array a by using p
for (int index=0; index<10; index++)
{
    cout<<p[index]<<" ";
}
cout<<endl;
// let us now change a by changing p
// let us double the entries of p
for (int index=0; index<10; index++)
{
    p[index]=2*index;
}

// let us print the entries of a by printing the entries of p

// print now the entries of the array a
for (int index=0; index<10; index++)
{
    cout<<a[index]<<" ";
}
cout<<endl;



return 0;
}

Exit mobile version