-1

I would like to know why this code is running.

code:

#include <stdio.h>

int main(int argc, char* argv[])
{
        char* c = "1234567";
        printf("%c\n", 5[c]);

        return 0;
}

result:

6

ExtremeBlue
  • 13
  • 2
  • 5

2 Answers2

4

If you are confused with the a[b] syntax, then just refresh your C knowledge.

a[b] is defined as *(a + b) and since a+b is the same as b+a, so is a[b] and b[a].

Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
0

In C , array indexing works as follows e.g a[i] it is actually interpreted by compiler as *(a+i) so it can be written as *(i+a) as addition is commutative. hence a[i] == i[a].

anshul garg
  • 473
  • 3
  • 7