<分区>
Possible Duplicate:
Negative array indexes in C?
我可以在数组中使用负索引吗?
#include <stdio.h>
int main(void)
{
char a[] = "pascual";
char *p = a;
p += 3;
printf("%c\n", p[-1]); /* -1 is valid here? */
return 0;
}
<分区>
Possible Duplicate:
Negative array indexes in C?
我可以在数组中使用负索引吗?
#include <stdio.h>
int main(void)
{
char a[] = "pascual";
char *p = a;
p += 3;
printf("%c\n", p[-1]); /* -1 is valid here? */
return 0;
}
最佳答案
是的,-1
在此上下文中有效,因为它指向分配给 char a[]
数组的内存中的有效位置。 p[-1]
等同于*(p-1)
。按照您示例中的分配链,它与有效的 a+3-1
或 a+2
相同。
编辑: 一般规则是整数和指针的加法/减法(以及指针上的等效索引操作)需要产生指向同一数组的结果或超出数组末尾的一个元素才能有效。谢谢,Eric Postpischil一个伟大的笔记。
关于c - 数组中的负索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12751918/