使用双指针访问2D数组元素 [英] Accessing 2D array elements using double pointer

查看:91
本文介绍了使用双指针访问2D数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在C接受了采访.面试官要我解释一下 如何使用double pointer访问2D array中的特定元素.我给出的答案为*(*(a+i)+j),其中a是双指针,i是行数,而j是列数.后来他让我用一个例子来解释.我对*(a+i)感到困惑,因为它提供的是值而不是地址,而添加到j则给出了一些垃圾值. 谁能解释一下.

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.

推荐答案

请记住,在一维数组中a[i]等于*(a+i). C中没有2D数组,只有数组的数组.

Remember that in a 1D array a[i] equals *(a+i). And there are no 2D arrays in C, just arrays of arrays.

所以a[i][j]实际上等于*(*(a+i)+j).

如果a的类型为int**,则(a+i)的类型仍为int**,则需要取消引用. *(a+i)的类型是int**(*(a+i)+j)的类型是int.

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.

关于面试问题,无论a是双指针,还是应该使用[]表示法.另一种选择是太麻烦了:

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];

这篇关于使用双指针访问2D数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆