Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is *(arr -1) the same as arr[-1]?

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading