C++ pointers and multidimensional array

The relation between a pointer and a linear array is such that if the array’s first address is assigned to a pointer,the pointer can access all the array elements either using the array syntax or the pointer form.Consider the code below.

Link Multidimensional array

int ar[]={2,3,45,4};
int *ipt=ar ;

cout<< ipt[0] << *(ipt+2) ; //work fine

2   45

In case of multidimensional array simply assigning the array’s first address to a pointer is just plain wrong.

int arrMul[3][5]={ {12 , 21 , 454 , 45 , 0} ,
{ 9 ,89 , 67 ,78 , 899} ,
{ 9129, 0 , 1 , 2 , 90 } } ;

int *ipt=arrMul; //error!!

Since a multidimensional array is an array of arrays,if we want the pointer to point to it we have to specify that the pointer which it is pointing to is a multidimensional array.We can do this by using the syntax
(*pointer)[column number]
.A code example is shown below.

int arrMul[3][5]={ {12 , 21 , 454 , 45 , 0} ,
{ 9 ,89 , 67 ,78 , 899} ,
{ 9129, 0 , 1 , 2 , 90 } } ;

int (*ipt)[5] = arrMul; //Work fine

cout<< ipt[2][4] ;//prints 90



Array of pointers and multidimensional array pointer

Sometimes people get confuse over the two syntax shown below.

int *ip[4] ;

int (*pt)[4] ;

The first syntax means an array of pointers and while the second pointer is a pointer to a multidimensional array having 4 columns.

An array of pointers means each element of the array,say ip[0] is simply a pointer that can point to another int variable or int array .And the element ip[1] is another pointer that can point to some other variable or array.Note here ip[0] and ip[1] have no relation at all.

Whereas in case of pointer ‘pt’ the pt[0] and pt[1] element will point to the first and second row of the same multidimensional array.Which means each element of ‘pt’ is bound to point to the elements of the same multidimensional array.

/*** Array of pointers example ***/
int *ip[4] ;

int arr[]={3,34,545,45} ,

ip[0]=arr ; //ip[0] points to arr array

ip[1]=&value ; //ip[1] points to value variable

cout<< ip[0][3] << endl //prints 45
<< *ip[1] ; //prints 9082

/*** multidimensional array pointer example ***/
int (*pt)[4] ;

pt=arr; //error! can only point to multidimensional array
pt[0]=arr ; //Error!!

int arMul[2][4]={0};

pt=arMul ; //work fine

Here you see for ‘ip’ pointer ,the ip[0] points to ‘arr’ and ip[1] points to different variable ‘value’ but in case of ‘pt’ pointing to ‘arr’ is wrong because it can only point to multidimensional array.