1. Home >
  2. Apps >
  3. Groups >

Tips for C Programmers

Question asked by malaka in #Coffee Room on Sep 20, 2012
malaka
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
kingdavid
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’.
Vishal Sharma
Vishal Sharma · Sep 20, 2012
Member of CrazyEngineers
kingdavid
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’.
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)
Neeraj Sharma
Neeraj Sharma · Sep 23, 2012
Member of CrazyEngineers
Vishal0203
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)
*(s+2) will give you s[2] i.e. h..

has is correct

You must log-in or sign-up to reply to this post.

Click to Log-In or Sign-Up