In C programming, consider the fixed-size array below. Will this program compile and what would be printed if it did? #include <stdio.h> int main() { char str[7] = "CuriousTab"; /* literal length exceeds array capacity */ printf("%s ", str); return 0; }

Difficulty: Easy

Correct Answer: Error

Explanation:


Introduction / Context:
This item checks knowledge of array initialization constraints in C. When an array is initialized with a string literal, the array must be large enough to store all characters plus the trailing null terminator.


Given Data / Assumptions:

  • str has size 7.
  • The literal "CuriousTab" has 10 characters.
  • A null terminator is required, making the minimum required size 11.


Concept / Approach:
When initializing char str[N] = "...";, the compiler enforces that N is at least the length of the literal plus one for '\0'. If it is not, the program is ill-formed and a diagnostic is required. Therefore compilation should fail.


Step-by-Step Solution:
Compute literal length: "CuriousTab" → 10 characters.Add the null terminator → 10 + 1 = 11 required.Provided size is 7 → insufficient → compile-time error.


Verification / Alternative check:
Changing the declaration to char str[] = "CuriousTab"; lets the compiler set the correct size (11). Alternatively, char str[11] also compiles.


Why Other Options Are Wrong:
Printing "CuriousTab" or saying “Cannot predict” assumes successful compilation, which does not happen given the size violation.


Common Pitfalls:
Forgetting that the null terminator consumes space, or assuming compilers will truncate or automatically resize the array.


Final Answer:
Error

More Questions from Strings

Discussion & Comments

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