Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the output be explained? [duplicate]

Tags:

c

pointers

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?

like image 725
user2227862 Avatar asked Dec 07 '22 07:12

user2227862


2 Answers

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?

like image 175
Grijesh Chauhan Avatar answered Dec 19 '22 04:12

Grijesh Chauhan


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).

like image 43
poorvank Avatar answered Dec 19 '22 04:12

poorvank