Search code examples
carraysindexingsemantics

Why do arrays with negative indexes work?


Possible Duplicate:
Negative array indexes in C?

How come this compiles, and runs as intended? I'm confused. I was just curious what would happen and to my surprise. It worked.

#include <stdio.h>
#include <conio.h>
int main(void)
{
    int i;
    int array[5];
    for(i = -1; i > -6; i--)
        array[i] = i*-1;
    for(i = -1; i > -6; i--)
        printf("%d\n",array[i]);
    getch();
}

Solution

  • It works, but it's just luck.

    An array is a pointer and when you declare it, it allocates some memory (for example from position 1 to position 6). Then the array points to the first element. When you increase the index, ti moves the pointer ahead.

    In your case, you're moving the pointer on the wrong side. But C doesn't care at all about it and write it's data on that memory block. Then it's able to retrieve that data.

    Be careful because when you read from a block of memory that is not allocated for your program, everything can happen. It doesn't mean that something wrong will happen, but it can. So, avoid it.

    Think to it as committing an offense. It doesn't mean you will be arrested, but there's the risk.