In C, what does this program print with %s given embedded null bytes inside the array literal? #include<stdio.h> #include<string.h> int main() { char str[] = "India\0\CURIOUSTAB\0"; printf("%s ", str); return 0; } Select the exact output.

Difficulty: Easy

Correct Answer: India

Explanation:

Introduction / Context:This examines how printf with the %s format specifier handles C strings that contain embedded null bytes. In C, a string is terminated by the first null byte; any content after the first 0 byte is not part of the printable string for %s.

Given Data / Assumptions:

  • An array initialized with "India\0\CURIOUSTAB\0".
  • printf("%s", str) prints characters until the first null byte.
  • The character encoding is ASCII-like so letters display ordinarily.

Concept / Approach:%s expects a pointer to a null-terminated byte sequence. The library reads characters sequentially, stopping at the first 0 byte. Thus, any bytes stored after the first null are ignored for printing via %s unless you print them separately by pointer arithmetic.

Step-by-Step Solution:The sequence at the array start is I n d i a followed by a null byte.printf("%s", str) reads characters until it reaches that null terminator.Therefore, only "India" appears on the output line.

Verification / Alternative check:If one printed &str[6] (i.e., a pointer into the array beyond the first null) and if the next segment were properly terminated, you could print "CURIOUSTAB". But with %s on str itself, output is just the first segment.

Why Other Options Are Wrong:CURIOUSTAB / India CURIOUSTAB / India\0CURIOUSTAB: They incorrectly assume that %s ignores or prints through the first null.None of the above: Incorrect because the program clearly prints "India".

Common Pitfalls:Confusing array storage with C-string semantics; forgetting that %s requires a single contiguous, null-terminated string starting at the given pointer.

Final Answer:India

More Questions from Strings

Discussion & Comments

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