数组中的负索引 [英] Negative index in array

查看:77
本文介绍了数组中的负索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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

Yes, -1 is valid in this context, because it points to a valid location in memory allocated to your char a[] array. p[-1] is equivalent to *(p-1). Following the chain of assignments in your example, it is the same as a+3-1, or a+2, which is valid.

EDIT:的一般规则是,对整数和指针进行加/减(并扩展为指针上的等效索引操作)需要产生一个结果,该结果指向同一数组或超出数组末尾的一个元素,以使其有效。谢谢 Eric Postpischil 的精彩演讲。

EDIT : The general rule is that an addition / subtraction of an integer and a pointer (and by extension, the equivalent indexing operations on pointers) need to produce a result that points to the same array or one element beyond the end of the array in order to be valid. Thanks, Eric Postpischil for a great note.

这篇关于数组中的负索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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