In C, a const pointer to char is used to modify a string buffer. What gets printed after changing the first character?
#include
int main()
{
char str[20] = "Hello";
char const p = str; / const pointer, modifiable characters */
*p = 'M';
printf("%s
", str);
return 0;
}
-
AMello
-
BHello
-
CHMello
-
DMHello
-
ENone of the above
Answer
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:
stris a writable character array containing "Hello".pis a const pointer to the first element ofstr.*p = 'M'overwrites the first character ofstr.
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