4

I am dealing pointers in c and when i run the following code i get "l" as the output! Why?

char *s = "Hello, World!";
 printf("%c", 2[s]);

What does 2[s] signify?

user2227862
  • 595
  • 3
  • 9
  • 16

5 Answers5

7

2[s] is same as s[2] because compiler convert both into *(2 + s)

here is a good link for you: why are both index[array] and array[index] valid in C?

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • Also note that it would not work for an arrays of larger types. since `s[2]` is actually `*(s+2*sizeof(char))`. If `s` was an array of integers, `2[s]` was still `*(2+s)`, but `s[2]` was `*(s*sizeof(int))`, which is equal to `8[s]`(assuming `sizeof(int)==4`). – Idan Arye May 22 '13 at 10:41
  • 5
    @IdanArye that's wrong. The expression `s+2` is always identical to `2+s`. Pointer arithmetic always works on multiples of the pointed-to type. – Graham Borland May 22 '13 at 10:43
  • 1
    @IdanArye That's interesting but I don't think it's right. Where did you read it? – Maroun May 22 '13 at 10:43
  • I stand corrected. I forgot that int is cast to the pointer type, not visa versa – Idan Arye May 22 '13 at 10:50
3

both s[2] and 2[s] are same. This is how the C compiler is built. Internally s[2] is treated as *(s+2). which is similar to 2[s].

3

This prints s[2] which is l. It's because s[i] is a syntactically equal to *(s + i). Therefore s[2] and 2[s] are both converted to *(s + 2).

poorvank
  • 7,524
  • 19
  • 60
  • 102
2

2[s] is same as s[2] which could be written as *(s+2).

Denny Mathew
  • 1,072
  • 9
  • 13
0

It is another way of writing s[2], they mean the same thing. In this case, it would print the 3rd character of your string, which is an 'l'

Salgar
  • 7,687
  • 1
  • 25
  • 39