Editing a printf format string in a writable array: what is printed? #include<stdio.h> int main() { char p[] = '%d '; // writable copy of the format p[1] = 'c'; // change '%d' to '%c' printf(p, 65); return 0; }

Difficulty: Easy

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\n'.
  • p[1] = 'c' changes the format to '%c\n'.
  • 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\n'.Modify to '%c\n'.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.

More Questions from Strings

Discussion & Comments

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