在C语言中使用指针算法访问2D数组元素 [英] Accessing 2D array elements using pointer arithmetic in C
问题描述
我有这段代码试图解决对指针,数组组合的疑问.
I have this code in which I've been trying to figure out a doubt on pointer,array combination.
int main()
{
int s[4][2] = {
{1234,56},
{1212,13},
{1434,80},
{1312,78}
};
printf("%d\n",s[2]);
printf("%d\n",*s[2]);
printf("%d\n",s+2);
printf("%d\n",*(s+2));
return 0;
}
怀疑是: 即使s [2]和(s + 2)指向相同的地址,为什么*(s [2])会打印值(即1434),而*(s + 2)会打印相同的地址却是(s + 2)已打印. *(s + 2)不是第3个1D数组地址(即s [2] [0])的平均值吗?
And the doubt is: Even though s[2] and (s+2) refer to the same address, why does *(s[2]) prints the value (i.e., 1434 ) but *(s+2) prints the same address what (s+2) has printed. Isn't *(s+2) mean value at address of 3rd 1D array(i.e., s[2][0])?
推荐答案
让我们看一下数组在内存中的外观:
Lets take a look at how your array look in memory:
+---------+---------+---------+---------+---------+---------+---------+---------+
| s[0][0] | s[0][1] | s[1][0] | s[1][1] | s[2][0] | s[2][1] | s[3][0] | s[3][1] |
+---------+---------+---------+---------+---------+---------+---------+---------+
^ ^ ^ ^
| | | |
&s[0][0] &s[0][1] &s[1][1] |
| | |
&s[0] &s[1] |
| | |
s[0] s[1] |
| | |
s s+1 |
| |
&s &s+1
现在让我们取s[0][0]
,您有五个可能指向该位置的指针:
Now lets take s[0][0]
, you have five possible pointers that can point to that location:
-
&s[0][0]
.这是int *
类型. -
&s[0]
.这是int (*)[2]
类型. -
s[0]
.这将衰减为指向s[0]
中第一个元素的指针,并等于1. -
s
.这将衰减为指向s
中第一个元素的指针,并等于2. -
&s
.指向类型为int (*)[4][2]
的数组的指针.
&s[0][0]
. This is of typeint *
.&s[0]
. This is of typeint (*)[2]
.s[0]
. This will decay to a pointer to the first element ins[0]
, and is equal to 1.s
. This will decay to a pointer to the first element ins
, and is equal to 2.&s
. A pointer to the array, of typeint (*)[4][2]
.
如您所见,您可以有许多不同的指针指向相同的位置,但是它们可能表示不同的东西,这在语义上造成了很大的不同.
As you can see you can have many different pointers to the exact same location, but they can mean different things which makes a whole lot of difference semantically.
这篇关于在C语言中使用指针算法访问2D数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!