How can the conclusion be explained?

I deal with 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] mean?

+4
source share
5 answers

Prints s [2] , which is equal to l. This is because s [i] is syntactically equal to * (s + i) . Therefore, s [2] and 2 [s ] are converted to * (s + 2).

+3
source

2[s] matches s[2] because the compiler converts both values ​​to *(2 + s)

here's a good link for you: why are both the [array] and array [index] indices valid in C?

+7
source

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

+3
source

2 [s] is the same as s [2], which can be written as * (s + 2).

+2
source

This is another way to write s[2] , they mean the same thing. In this case, it will print the third character of your string, which is "l"

0
source

Source: https://habr.com/ru/post/1482133/


All Articles