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;
}
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;
}
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.
p[-1] is equivalent to p-1 should be read as p[-1] is equivalent to *(p-1)6.5.6 Additive operators
8 ...if the expressionPpoints to the i-th element of an array object, the expressions(P)+N(equivalently,N+(P)) and(P)-N(whereNhas the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist....
Emphasis mine. So, in your specific example, p[-1] is valid, since it points to an existing element of a; however, a[-1] would not be valid, since a[-1] points to a non-existent element of a. Similarly, p[-4] would not be valid, a[10] would not be valid, etc.
Of course it is valid.
(C99, 6.5.2p1) "One of the expressions shall have type ‘‘pointer to object type’’, the other expression shall have integer type, and the result has type ‘‘type’’.
Generally using such negative indexes is a Bad Idea(TM). However, I found one place where this can be useful: trig lookup tables. For such a look up table, we need to use some angle measure as the index. For example, I can index sin values for angles between -180 degrees and +180 using degrees as an index. Or if I want to use radions instead, I can use a multiple of some fraction of PI, say PI/3, for the index. Then I can get cos values between -PI and PI by multiples of PI/3.
Yes, this is legal, as C lets you do unsafe pointer arithmetic all day. However, this is confusing, so don't do it. See also this answer to the same question.
pis not an array, it's a pointer into an array.ais an array and a negative index forawill always be invalid.int x = *(int*)NULL;Would you call that valid? You can prove that the code results in UB via static analysis, so I would say no.0at first, but that was my mistake. I quickly edited and replaced it withNULL. Again, it comes down to what you define as "valid". I think most people would go beyond "does the program compile?", it is a more useful definition.