Tips for C Programmers
Question asked by malaka in #Coffee Room on Sep 20, 2012

malaka · Sep 20, 2012
Member of CrazyEngineers
What is Output of following c snippet?
int main(){
char *s="Abhas";
printf("%s",s+ 2);
getch();
} Posted in: #Coffee Room
int main(){
char *s="Abhas";
printf("%s",s+ 2);
getch();
} Posted in: #Coffee Room

kingdavid · Sep 20, 2012
Member of CrazyEngineers
has
Explanation: In the above program role of %s is to display the string whose address is passed as an argument. This is how a standard printf statement works in c language. Now since we have passed s + 2 as an argument therefore first value of this expression is evaluated. Here ‘s’ would refer to address of first character in string ‘s’. Now printf would get address of third character (address of first character + 2) as argument so it will display the string starting from third position. Hence output would be ‘has’.
Explanation: In the above program role of %s is to display the string whose address is passed as an argument. This is how a standard printf statement works in c language. Now since we have passed s + 2 as an argument therefore first value of this expression is evaluated. Here ‘s’ would refer to address of first character in string ‘s’. Now printf would get address of third character (address of first character + 2) as argument so it will display the string starting from third position. Hence output would be ‘has’.

Vishal Sharma · Sep 20, 2012
Member of CrazyEngineers
Ummm... don't you think there must be a * in front of s+2 to get the output "has" ? What i actually mean is, to get the output "has", it must be *(s+2)kingdavidhas
Explanation: In the above program role of %s is to display the string whose address is passed as an argument. This is how a standard printf statement works in c language. Now since we have passed s + 2 as an argument therefore first value of this expression is evaluated. Here ‘s’ would refer to address of first character in string ‘s’. Now printf would get address of third character (address of first character + 2) as argument so it will display the string starting from third position. Hence output would be ‘has’.

Neeraj Sharma · Sep 23, 2012
Member of CrazyEngineers
*(s+2) will give you s[2] i.e. h..Vishal0203Ummm... don't you think there must be a * in front of s+2 to get the output "has" ? What i actually mean is, to get the output "has", it must be *(s+2)
has is correct