Accessing 2D array elements using double pointer

2020-07-27 03:11发布

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.

2条回答
淡お忘
2楼-- · 2020-07-27 03:22

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];
查看更多
家丑人穷心不美
3楼-- · 2020-07-27 03:42

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*

查看更多
登录 后发表回答