C strings and the null terminator: what does this program print?
#include
#include
int main()
{
static char s[] = "Hello!";
printf("%d
", *(s + strlen(s)));
return 0;
}
-
A8
-
B0
-
C16
-
DError
-
E33
Answer
Correct Answer: 0
Explanation
Introduction / Context:This question checks your knowledge of how strlen works and what lies at the first index past the last character in a C string. It emphasizes the importance of the null terminator '\0'.
Given Data / Assumptions:
- s is "Hello!" which has 6 visible characters.
- strlen(s) returns the number of characters before the null terminator, so strlen(s) = 6.
- s is a proper C string with s[6] == '\0'.
Concept / Approach:C strings end with a null byte, numeric value 0. The expression s + strlen(s) points exactly to that null byte. Dereferencing it with *(...) yields the char value 0, which then promotes to int when printed with %d.
Step-by-Step Solution:Compute n = strlen(s) → 6.Pointer arithmetic: s + n points to s[6], the null terminator.Dereference *(s + n) → value is '\0', whose integer value is 0.printf("%d", 0) prints 0.
Verification / Alternative check:Printing as a character with "%c" would not show a printable symbol because '\0' is non-printing. Using s[n-1] would print '!' with value 33 if printed as %d.
Why Other Options Are Wrong:Numbers like 8, 16, or 33 correspond to other characters or guesses and are unrelated to the null byte here. “Error” is incorrect because the code is valid and well-defined.
Common Pitfalls:Off-by-one errors around string ends; assuming strlen counts the terminator; mixing character codes with visible characters without confirming the exact index.
Final Answer:0