Home > Mobile >  Array of pointer to arrays in C
Array of pointer to arrays in C

Time:08-19

In C is possible to create a pointer to a 2-D array of certain dimensions like this:

int(*ptr)[n] = A

where "ptr" is the pointer to create and A is the pointer to the first row in the array (and n in the number of columns). Thus, this code will work:

int Arr[3][3]
int (*ptr)[3] = Arr;

Now, my question is "How I create an array of pointers like ptr?"

CodePudding user response:

How I create an array of pointers like ptr?

There are different ways of doing this as shown below.

Method 1

We can use decltype with modern C :

int Arr[3][3]{};       //Arr is a 2d array of type int [3][3]
int (*ptr)[3] = Arr;  //ptr is a pointer to an array of size 3 with elements of type int 


//lets create an array of pointers like ptr 
decltype(ptr) f[10] ={ptr};    //f is an array of size 10 with elements of type int (*)[3]

Method 2

Here we explicitly write the type of the array f without using decltype

int Arr[3][3]{};       //Arr is a 2d array of type int [3][3]
int (*ptr)[3] = Arr;  //ptr is a pointer to an array of size 3 with elements of type int 


//lets create an array of pointers like ptr 
int (*f[10])[3] = {ptr};       //f is an array of size 10 with elements of type int (*)[3]

CodePudding user response:

Now, my question is "How I create an array of pointers like ptr?"

int (*x[10])[5];

x is an array of 10 pointers to array of 5 int

And the initialization example:

int a[3][4];
int b[5][4];
int c[7][4];

int (*ptr[3])[4] = {a,b,c};
  • Related