Difficulty: Easy
Correct Answer: Mello
Explanation:
Introduction / Context:
This question differentiates between a const pointer to char and a pointer to const char. The declaration char *const p
means the pointer value itself is constant (cannot point elsewhere), but the characters it points to remain modifiable.
Given Data / Assumptions:
str
is a writable character array containing "Hello".p
is a const pointer to the first element of str
.*p = 'M'
overwrites the first character of str
.
Concept / Approach:
Because the data is in an array (not a string literal in read-only memory), writing *p = 'M'
replaces 'H' with 'M'. The rest of the array is unchanged. Printing str
therefore shows the modified word.
Step-by-Step Solution:
Start with "Hello" → indices: 0:H 1:e 2:l 3:l 4:o.Apply *p = 'M'
→ index 0 becomes 'M'.Array now spells "Mello".printf prints the entire string → "Mello".
Verification / Alternative check:
Had the pointer been declared as const char *p
, then writing *p = 'M'
would be illegal. Here, only the pointer is const, not the data.
Why Other Options Are Wrong:
"Hello" ignores the assignment. "HMello" or "MHello" would require insertions or different pointer manipulations not present in the code.
Common Pitfalls:
Confusing char *const
with const char *
and assuming data immutability. Also, trying this with a string literal (e.g., char *p = "Hello";
) would cause undefined behavior.
Final Answer:
Mello
Discussion & Comments