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?
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?
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?
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].
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).
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'