This question already has an answer here:
这个问题在这里已有答案:
- What does s[-1] = 0 mean? 6 answers
s [-1] = 0是什么意思? 6个答案
I was trying the below code snippet. Please help me in understanding how the o/p is coming as 2? What does p[-2]
mean here?
我正在尝试下面的代码片段。请帮助我理解o / p如何成为2? p [-2]在这里是什么意思?
int main(void){
int ary[4] = {1, 2, 3, 6};
int *p = ary + 3;
printf("%d\n", p[-2]);
}
2 个解决方案
#1
5
ary
is an array of four int
s. This will be put in memory like this:
ary是四个整数的数组。这将被放在内存中,如下所示:
| 1 | 2 | 3 | 6 |
^ ^ ^
| | |
ary p - 2 p
By saying p = ary + 3
, you're setting p
to the address of the fourth element in the array. So, p
is pointing to 6
. p[-2]
is equal to *(p - 2)
. That means you point p
to the second element in the array, and access its value: 2
.
通过说p = ary + 3,你将p设置为数组中第四个元素的地址。因此,p指向6. p [-2]等于*(p-2)。这意味着您将p指向数组中的第二个元素,并访问其值:2。
#2
0
int *p = ary + 3
points to ary[3] so if you move the pointer two steps back you will get ary[1]
int * p = ary + 3指向ary [3]因此,如果你将指针向后移动两步,你将获得ary [1]
#1
5
ary
is an array of four int
s. This will be put in memory like this:
ary是四个整数的数组。这将被放在内存中,如下所示:
| 1 | 2 | 3 | 6 |
^ ^ ^
| | |
ary p - 2 p
By saying p = ary + 3
, you're setting p
to the address of the fourth element in the array. So, p
is pointing to 6
. p[-2]
is equal to *(p - 2)
. That means you point p
to the second element in the array, and access its value: 2
.
通过说p = ary + 3,你将p设置为数组中第四个元素的地址。因此,p指向6. p [-2]等于*(p-2)。这意味着您将p指向数组中的第二个元素,并访问其值:2。
#2
0
int *p = ary + 3
points to ary[3] so if you move the pointer two steps back you will get ary[1]
int * p = ary + 3指向ary [3]因此,如果你将指针向后移动两步,你将获得ary [1]