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;
}
}
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.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development