Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will the following C code do?

char *strrchr(const char *s, int c)
{
    char ch = c;
    const char *sc;
    for (sc = NULL; ; ++s)
    {
        if (*s == ch)
            sc = s;
        if (*s == '\0')
            return (char *) sc;
    }
}

  • A.find last occurrence of c in char s[ ].
  • B.find first occurrence of c in char s[ ].
  • C.find the current location of c in char s[ ].
  • D.There is error in the given code

Answer: A

Correct answer: find last occurrence of c in char s[ ].

The loop walks the whole string, and every time it meets the character it records the position in sc, overwriting any earlier one. Only when it reaches the terminating null does it return, so what comes back is the position of the last occurrence - or NULL if there was none. Testing for the null after the comparison is what lets a search for '\0' itself succeed.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.