Recently I had an Interview in C
. The interviewer has asked me to explain
how to access particular element in 2D array
using double pointer
. I gave the answer as *(*(a+i)+j)
, where a
is a double pointer, i
is number of rows and j
is number of columns. Later he asked me to explain using an example. I am confused at *(a+i)
as it gives value instead of address and adding to j
gives some junk value.
Can anyone please explain.

- 3,999
- 17
- 54
- 74

- 52
- 1
- 7
2 Answers
Remember that in a 1D array a[i]
equals *(a+i)
. And there are no 2D arrays in C, just arrays of arrays.
So a[i][j]
is actually equal to *(*(a+i)+j)
.
If the type of a
is int**
, then the type of (a+i)
is still int**
, you need to dereference it. Type of *(a+i)
is int*
and the type of *(*(a+i)+j)
is int
.
About the interview question, no matter that a
is a double pointer, you should still use the []
notation. The alternative is too cumbersome:
int **a = ...;
int x = a[i][j];

- 94,151
- 12
- 143
- 190
-
1*"there are no 2D arrays in C"* is somewhat incorrect. Double pointer `int **a;` can be used as 2D array with array of arrays approach, but `int a[N][M];` is true 2D array. – user694733 May 12 '15 at 10:54
-
@user694733: Well, that's a matter of definition. `int a[N][M]` can be seen as a 2D array or as an array of N values of type `int[M]`, that is an array of arrays. Other languages that have true 2D arrays would use `a[i,j]` instead of `a[i][j]`. – rodrigo May 12 '15 at 11:03
The a[i][j] element looks like
a[i][j]=*(*(a+i)+j)
So it is a double pointer because it first determines the row and then the column, as you can see the 2d matrix looks like
----- _________________
|___| ---> |___|____|____|___|
|___| ---> |___|____|____|___|
|___| ---> |___|____|____|___|
|___| ---> |___|____|____|___|
actually you can see that a one dimensional which holds the address of another one dimensional matrix. So the first vertical matrix data type is int**
because it holds the address another one dimensional which is int*

- 478
- 7
- 22