CrazyEngineers
  • Tips for C Programmers

    malaka

    Member

    Updated: Oct 27, 2024
    Views: 1.3K
    What is Output of following c snippet?
    int main(){
    char *s="Abhas";
    printf("%s",s+ 2);
    getch();
    }
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • kingdavid

    MemberSep 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’.
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberSep 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)
    Are you sure? This action cannot be undone.
    Cancel
  • Neeraj Sharma

    MemberSep 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
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register