Relation between pointers and array in C++

In C++,array and pointers are closely related to one another.The array syntax is just another way to form of pointers.To understand what this means we will have to look at how compiler interpret an array.

Frankly speaking the compiler does not know what an array is.Whenever it come across an array say a variable name with a subscript arr[2] ,it will interpret this syntax to the pointer form.The arr[2] is interpreted as *(arr+2).Looking at this form the compiler understand which address/storage to access(the address of the storage 2 times away from ‘arr’ address) and output the value accordingly.

Link : C++ array

Whenever you use an array we can directly use it’s pointer form instead of the subscript syntax to access the value.Consider the code below.

int arr[]={ 45 , 90 , 536 };

cout<< *(arr+1) << endl //Array pointer form
<< arr[1] << endl ; //acessing value with subscript

Output
 
90   90


Assigning array to pointer

You can use pointer to access any array.To do this the first address of the array must be assigned to the pointer.Once the pointer is assigned to the first address you can access all the values using the pointer by incrementing the address which can be done by adding value.

In any array the name of the array (without the subscript) gives the first address of the array.For instance in an array ‘arr[4]’, the name ‘arr’ gives the address of the first storage in the array.You can also simply add an ‘&'(ampersand) in front of the first array element to get the address.

int arr[]={ 12 , 45 , 59 };

int *arrPt=arr; //work fine
// or arrPt=&arr[0] //work fine too

/*** Accessing all the array elements ***/
for( int i=0 ; i<sizeof(arr)/sizeof(int) ; i++ )
{
cout<< *(arrPt+1) << ” ” ;
}

Output

12   45   59

Once the pointer is assigned the first address of the array we can also use the subscript syntax with the pointer to access the array.This is another proof of how closely the array and pointer are related; pointer behave like an array.

Note:include <cstring> to use the strlen() function.This function gives the number of characters in a string.

char str[]=”New string” ;

char *cPt=str ;

for(int i=0; i<strlen(str) ; i++ )
{
cout<< cPt[i] << ” ” ; ///work fine
}

Output
 
New string



Leave a Reply

Your email address will not be published. Required fields are marked *