Question 1Medium
What will be the output of the program?
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "COMP\0\RIDER\0";
printf("%d\n", strlen(str));
return 0;
}- 12
- 5
- 4
- 15
Answer: C. 4
Explanation
The function strlen returns the number of characters int the given string.
Therefore,
strlen(str) becomes strlen("COMP")contains 4 characters.
A string is a collection of characters terminated by '\0'.The output of the program is "4".
Step-by-step solution
- The string literal is COMP, then a NUL character, then R, I, D, E, R and another NUL.
- Strlen counts characters only up to the first NUL, not to the end of the array.
- It counts C, O, M and P, which is 4.
- The answer is 4.
Why the other options are wrong
- A. 12 is not the count, because strlen stops at the first NUL.
- B. 5 would count the NUL, but strlen stops before it.
- D. 15 is not the count, because strlen stops at the first NUL.
Tip: Strlen stops at the first zero byte, so an embedded zero cuts the string short.