Tips for C Programmers

malaka

malaka

@malaka-wboxAY Oct 27, 2024
What is Output of following c snippet?
int main(){
char *s="Abhas";
printf("%s",s+ 2);
getch();
}

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • kingdavid

    kingdavid

    @kingdavid-1gQln4 Sep 19, 2012

    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

    @vishal-pysGmK Sep 20, 2012

    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

    @neeraj-iAaNcG Sep 23, 2012

    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