In C, what is sizeof for this compound string with embedded nulls? #include<stdio.h> int main() { char str[] = "India\0CURIOUSTAB\0"; printf("%d ", sizeof(str)); return 0; }

Difficulty: Medium

Correct Answer: 18

Explanation:


Introduction / Context:
This question probes the difference between string length and array size, especially when the string literal contains explicit null characters within it. sizeof on an array returns the total storage in bytes, not the length up to the first null.



Given Data / Assumptions:

  • The initializer is a string literal: "India\0CURIOUSTAB\0".
  • Characters before the compiler’s implicit terminator are all included, including explicit \0 escapes.
  • Array str is defined with automatic sizing from the initializer.


Concept / Approach:
For a string literal, the compiler constructs a sequence of characters exactly as written, then appends one extra null terminator at the end of the entire literal. Therefore, each explicit \0 is counted in the array, and an additional trailing \0 is still appended by the compiler.



Step-by-Step Solution:
"India" → 5 letters.First \0 → +1 byte (embedded terminator)."CURIOUSTAB" → 10 letters.Second explicit \0 → +1 byte.Compiler’s final implicit \0 → +1 byte.Total size = 5 + 1 + 10 + 1 + 1 = 18 bytes.


Verification / Alternative check:
Compare with strlen(str), which would return 5 because it stops at the first null. sizeof returns 18 because it measures the entire storage of the array object.



Why Other Options Are Wrong:
(17) forgets the compiler’s final implicit null. (12) and (16) undercount by ignoring embedded or trailing nulls. (11) is unrelated to the constructed sequence.



Common Pitfalls:
Equating sizeof with strlen; believing that an explicit trailing \0 suppresses the compiler’s implicit one (it does not).



Final Answer:
18

More Questions from Strings

Discussion & Comments

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