Editing a printf format string in a writable array: what is printed?
#include
int main()
{
char p[] = '%d
'; // writable copy of the format
p[1] = 'c'; // change '%d' to '%c'
printf(p, 65);
return 0;
}
-
AA
-
Ba
-
Cc
-
D65
-
E%c
Answer
Correct Answer: A
Explanation
Introduction / Context:Unlike string literals, a char array initialized from a literal is writable. This program modifies a local copy of the format string to change the conversion specification from decimal integer (%d) to character (%c) and then prints an ASCII/character code.
Given Data / Assumptions:
- p is a char array containing '%d'.
- p[1] = 'c' changes the format to '%c'.
- printf receives 65 as the argument for %c.
Concept / Approach:For the %c conversion, printf outputs the character whose code is the integer argument. 65 in ASCII corresponds to 'A'. Therefore, the program prints 'A' followed by a newline.
Step-by-Step Solution:
Initial format → '%d'.Modify to '%c'.printf → interprets 65 as a character → outputs 'A' then newline.Verification / Alternative check:Change 65 to 97 and you will see 'a'. Revert the format to '%d' to see the decimal number printed.
Why Other Options Are Wrong:
'a': would require 97.'c': would print the literal letter only if the format were '%%c'.'65': would require %d.'%c': not printed; it is a directive.Common Pitfalls:Attempting to modify a string literal directly (undefined behavior) instead of modifying a writable array copy.
Final Answer:A.