Difficulty: Medium
Correct Answer: lice ice ce e
Explanation:
Introduction / Context:
This problem explores pointer arithmetic on C strings and how %s
prints from the first \0
encountered onward. It also contains a deliberate twist: writing to a string literal via *x = ...
. That write is undefined behavior in standard C and can crash; however, many textbook problems assume it “works” for demonstration purposes. We follow that intent here.
Given Data / Assumptions:
x
initially points to the literal "Alice"
(bytes: A l i c e \0).
Concept / Approach:
*x = x[n] sets the first byte to \0. Thus, at the original location, the string becomes empty. The remainder of the bytes still contain l i c e \0
. Advancing the pointer by one then points to "lice"
, which prints fully; further increments produce suffixes.
Step-by-Step Solution:
Before assignment: [A][l][i][c][e][\0]After *x = x[n]: [\0][l][i][c][e][\0]i = 0 → prints "" (empty), pointer moves to li = 1 → prints "lice"i = 2 → prints "ice"i = 3 → prints "ce"i = 4 → prints "e"i = 5 → prints ""Ignoring the empty prints, the visible output is: lice ice ce e
Verification / Alternative check:
If char x[] = "Alice";
(array, not literal), the write is valid and the same visible output results.
Why Other Options Are Wrong:
(a) and (c) would require the first byte to remain 'A'
. (b) is reversal, which this code does not do. (e) can happen in real systems but the exercise assumes otherwise.
Common Pitfalls:
Forgetting that %s
prints until \0
and that pointer increments shift the starting point; overlooking undefined behavior of modifying string literals.
Final Answer:
lice ice ce e
Discussion & Comments