In C, what will be the exact output of this program (note the embedded nulls and how strlen works)? #include<stdio.h> #include<string.h> int main() { char str[] = "India\0\CURIOUSTAB\0"; printf("%d ", strlen(str)); return 0; } Choose the correct value printed by strlen.

Difficulty: Easy

Correct Answer: 5

Explanation:


Introduction / Context:
This question tests understanding of C strings, the effect of the null terminator (the byte with value 0), and the standard library function strlen. In C, strings are sequences of characters terminated by a null byte, and library functions stop at the first null byte regardless of any additional characters that may exist afterward in the same array.



Given Data / Assumptions:

  • The character array literal is initialized as "India\0\CURIOUSTAB\0".
  • In C string handling, the first null byte marks the end of the string for functions like strlen and printf with %s.
  • strlen counts characters up to but not including the first null terminator.
  • We assume a typical hosted C implementation following the standard rules for string functions.


Concept / Approach:
strlen(s) returns the number of characters before the first 0 byte in s. Any bytes after the first 0 are ignored for length purposes, even if they are part of the same array. Thus, only the leading segment prior to the first null contributes to the length.



Step-by-Step Solution:
The array begins with the bytes for the letters I n d i a.Immediately after these 5 letters, there is a null terminator (\0).strlen examines bytes starting at str[0] and stops as soon as it encounters the first 0 byte.Therefore, strlen("India\0...") returns 5.The trailing characters like C U R I O U S T A B and any later nulls are ignored by strlen.



Verification / Alternative check:
Printing with printf("%s", str) would output only "India" for the same reason (stopping at the first null). Using sizeof(str) would count the entire array length including all bytes and nulls, which is different from strlen.



Why Other Options Are Wrong:
10 / 11 / 6: These treat the post-null bytes as part of the length, which strlen never does.None of the above: Incorrect because 5 is valid and exact.



Common Pitfalls:
Mistaking the array's allocated size for the string length; assuming embedded nulls are ignored; thinking escape sequences like \C change length (they do not extend the first segment before the null).



Final Answer:
5

More Questions from Strings

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion