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.
相关问题
- Multiple sockets for clients to connect to
- Do the Java Integer and Double objects have unnece
- What is the best way to do a search in a large fil
- How to get the maximum of more than 2 numbers in V
- Faster loop: foreach vs some (performance of jsper
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
isint**
, then the type of(a+i)
is stillint**
, you need to dereference it. Type of*(a+i)
isint*
and the type of*(*(a+i)+j)
isint
.About the interview question, no matter that
a
is a double pointer, you should still use the[]
notation. The alternative is too cumbersome:The a[i][j] element looks like
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 isint*