1

This question was asked in a recent exam where the candidate had to find the output for the following code:

#include<stdio.h>
#include<string.h>
int main()
{
    char * c = "GATECSIT2017";
    char *p = c;
    printf("%d", (int)strlen(c+2[p]-6[p]-1));
    return 0;
}

I started coding in C++ , so I wasn't an expert in C-Strings. After messing around with code, I understood how it worked, but one thing wasn't clear to me, which was this way of accessing a char from the char* string.

My question is, how 2[p] gets the character at index 2? Does it resolve into *(p+2) or is there something else going on? Also, is there any documentation or any article that could explain this behavior?

Community
  • 1
  • 1
RishbhSharma
  • 259
  • 3
  • 10

1 Answers1

5

For any array or pointer a and index i, the expression a[i] is equal to *(a + i).

Because of the commutative property of + the expression *(a + i) is equal to *(i + a), which according to the first equality is equal to i[a], i.e. switching place of the index and pointer/array.

So in your case the expression 2[p] is equal to *(2 + p) which is equal to *(p + 2) which is equal to p[2].

Using e.g. 2[p] is only for (bad) obfuscation so please don't use it anywhere.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • You made it very clear. How the index is resolved and the commutative property of the + operator lead to 2[p] being same as p[2]. – RishbhSharma Jun 03 '17 at 15:20
  • Could you point to some resource that tells the behavior of [] ? Or any other resources related to this question? – RishbhSharma Jun 03 '17 at 15:25
  • 1
    @RishbhSharma [Here's a reference about the array subscript operator](http://en.cppreference.com/w/c/language/operator_member_access#Subscript). – Some programmer dude Jun 03 '17 at 15:27