I'm trying to solve this question that has a vector and there is a pointer that leads to an negative index. I'd like to know if C ignores it and considers it as a positive number or it goes backwards in the vector, like -1 being the last element of the array.
CodePudding user response:
Yes, you can have negative indexes. This follows from the definition of pointer arithmetic in C, namely that p[i]
is exactly equivalent to *(p i)
, and it's perfectly legal for i
to be a negative number.
So, no, the sign is not ignored. Also, if you're dealing directly with an array, there's no rule that says that a negative index is computed with respect to the end of the array. If you're dealing directly with an array, a negative index ends up trying to access memory "off to the left" of the beginning of the array, and is quite against the rules, leading to undefined behavior.
You might wish to try this illustrative program:
#include <stdio.h>
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int *p = &arr[4];
int *endp = &arr[8];
printf("%d %d %d\n", arr[0], arr[4], arr[8]); /* prints "1 5 9" */
printf("%d %d %d\n", p[-1], p[0], p[1]); /* prints "4 5 6" */
printf("%d %d %d\n", endp[-2], endp[-1], endp[0]); /* prints "7 8 9" */
printf("x %d %d x\n", arr[-1], endp[1]); /* WRONG, undefined */
}
The last line is, as the comment indicates, wrong. It attempts to access memory outside of the array arr
. It will print "random" garbage values, or theoretically it might crash.
CodePudding user response:
Is *(arr -1) the same as arr[-1]?
Yes. Strictly speaking, the array subscripting []
operator is defined as arr[n]
being equivalent to *( (arr) (n) )
. In this case: *( (arr) (-1) )
.
or it goes backwards in the vector
Well it goes backwards until it reaches array item 0, from there on you access the array out of bounds. It doesn't "wrap around" the index or anything like that. Example:
int arr[3] = ...;
int* ptr=arr 1;
printf("%d\n", ptr[-1]); // ok, prints item 0
int* ptr=arr;
printf("%d\n", ptr[-1]); // not ok, access out-of-bounds.
CodePudding user response:
According to the C Standard (6.5.2.1 Array subscripting)
2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1) (E2))). Because of the conversion rules that apply to the binary operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).
So the expression arr[-1]
is evaluated as *( arr -1 )
that is the same as *( arr - 1)
.
However pay attention to that arr[-1]
is not the same as -1[arr]
because before the square brackets there must be a postfix expression
postfix-expression [ expression ]
and the unary minus operator has less precedence than a protfix expression.
But you may write ( -1 )[arr]
that is the same as arr[-1]
.