February 01, 2014

Funny thing with arrays in C

It's a funny thing that C does not really have arrays. It has something that looks like an array but is really a pointer to a memory location. There is an array indexing expression, array[index], that is just shortcut for the expression (*(array + index)). Therefore it’s equally valid to write index[array], which is also shortcut for (*(array+index)). Just a pure commutative operation. Powurrrful way to shoot yourself in a leg.

So, look at this piece of code:

#include <stdio.h>

int main(int argc, char const** argv)
{
    char* str = "test";

    printf("%c\n", 0[str]);
    printf("%c\n", *(str+1));
    printf("%c\n", *(2+str));
    printf("%c\n", str[3]);

    return 0;
}

Do you think this will blow up? Heh, no way! Watch this out.

No comments:

Post a Comment