int main()
{
int (*x)[5]; //pointer to an array of integers
int y[6] = {1,2,3,4,5,6}; //array of integers
int *z;
One should understand the internal representation of (*x)[i]
. Internally, it is represented as
*((*x)+i)
, which is nothing but the ith element of the array to which x is pointing. This is also a way to have a pointer pointing to 2d array. The number of rows is irrelevant in a 2d array.
For example:
int arr[][2]={{1,2},{3,4}};
int (*x)(2);
x=arr; /* Now x is a pointer to the 2d array arr.*/
Here x
is pointing to a 2d array having 2 integer values in all columns, and array elements are stored contiguously. So (*x)[0]
will print arr[0][0]
(which is 1), (*x)[1]
will print the value of arr[0][1]
(which is 2) and so on. (*x+1)[0]
will print the value of arr[1][0]
(3 in this case) (*x+1)[1]
will print the value of arr[1][1]
(4 in this case) and so on.
Now, a 1d array could be treated as nothing but a 2d array having only one row with as many columns.
int y[6] = {1,2,3,4,5,6};
int (*x)[6];
x =y;
This means x
is a pointer to an array having 6 integers. So (*x)[i]
which is equivalent to *((*x)+i)
will print ith index value of y
.