This is because int **d2
is a pointer to pointer. There is no such thing as 2d pointer.
For example, lets consider 1d array:
int a[2] = {1, 2};
Now, an integer pointer will point to the first element of the array if assigned as follows:
int *d = a;
Talking about pointer to pointers, a pointer to pointer points to a memory location which holds address of other pointer!
For example,
// This will declare an integer pointer
int *a;
The above pointer will store address of some other variables.
For example, you can assign values to it as follows:
int x = 5;
int *a = &x;
Now, here is what a pointer to pointer does:
A pointer to pointer holds memory address of other pointers.
This means that, in the above example we can declare a pointer to pointer that holds address of pointer a
:
int x = 5;
int *a = &x;
// A pointer to pointer
int **b = &a;
// To print value of x using b
printf("%d", **b);
The above code can be understood as follows:
- a = &x; so *a = *(&x) = 5
- b = &a; so *b = *(address in b) = *(address of a) = address of x
- But **b = *(*b) = *(address of x) = 5
Hope this clears your confusion about pointer to pointers.
Now, coming towards your use case, if you want a pointer to point to your 2d integer array, you can just use a pointer and assign it the address of first element of the array. This can be done as follows:
int a[2][2] = {{1, 2}, {3, 4}};
// Declare a pointer that points to first element of array
int *b = &a[0][0];
Now if you want to access the element a[i][j]
of this array using pointer, you can access it as b + 2*i + j
.
In general, if the dimensions of array is p*q
, the element a[i][j]
can be accessed using b + q * i + j
.
For example, to print the array using 2 for loops,
int rows = 2;
int cols = 3;
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int *b = &a[0][0];
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
// Print a[i][j] using pointer b
printf("%d ", *(b + cols * i + j));
}
}
// 1 2 3 4 5 6
You can also use single loop,
int rows = 2;
int cols = 3;
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int *b = &a[0][0];
for(int i=0; i<rows*cols; i++) {
printf("%d ", *(b + i));
}
// 1 2 3 4 5 6