Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative index in array [duplicate]

Tags:

arrays

c

Possible Duplicate:
Negative array indexes in C?

Can I use negative indices in arrays?

#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;
}
like image 931
David Ranieri Avatar asked Oct 05 '12 18:10

David Ranieri


People also ask

What will happen if array index is negative?

JavaScript arrays are collections of items, where each item is accessible through an index. These indexes are non-negative integers, and accessing a negative index will just return undefined .

Is negative indexing possible in array?

Python programming language supports negative indexing of arrays, something which is not available in arrays in most other programming languages. This means that the index value of -1 gives the last element, and -2 gives the second last element of an array. The negative indexing starts from where the array ends.

Can we have negative indexes in array in C++?

That means that you can have a pointer to the middle element of an array, and use it with a positive or negative index, and it's simple arithmetic. That is, negative indexes here will be out of bounds of the array, and will lead to undefined behavior.

What Cannot accept negative indexes?

substr deals with a starting offset and a length. It makes sense to me that substring does not allow a negative index, because there really isn't a such thing as a negative index (the characters in a string are indexed from 0 to n, a "negative index" would be out of bounds).


1 Answers

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 : 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.

like image 157
Sergey Kalinichenko Avatar answered Oct 06 '22 08:10

Sergey Kalinichenko