使用负数作为数组索引 [英] Using negative number as array index
问题描述
我沿着询问以下的输出有竞争力的问题就来了:
I came along a competitive question that asks the output of the following:
#include <stdio.h>
int main()
{
int a[] = {0,1,2,3,4};
int i, *ptr;
for(ptr = a+4, i=0; i <=4; i++)
printf("%d", ptr[-i]);
return 0;
}
我看过这个话题:负数组索引用C 的不过是我不清楚如何-ve符号生成以相反的顺序,即该阵列。 4,3,2,1,0
。
I did read this topic: Negative array indexes in C? However it was unclear to me how the -ve symbol generates the array in the reverse order, ie. 4, 3, 2, 1, 0
.
推荐答案
首先,记得在C中的前pression PTR [指数]
意味着同样的事情为 *(PTR +指数)
。
First, recall that in C the expression ptr[index]
means the same thing as *(ptr+index)
.
现在让我们来看看再次你的前pression: PTR
前设置为 A + 4
循环;然后你申请 -i
指标吧。因此,等效指针运算前pression将如下:
Now let's look at your expression again: ptr
is set to a+4
before the loop; then you apply -i
index to it. Therefore, the equivalent pointer arithmetic expression would be as follows:
printf("%d", *(a+4-i));
这前pression遍历数组倒退,生产,你看到的结果。
This expression iterates the array backwards, producing the results that you see.
这篇关于使用负数作为数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!