In C programming, what will be the output of the following code? Carefully consider pointer arithmetic on a string and the postfix increment. #include <stdio.h> int main() { char str[] = "peace"; char s = str; printf("%s ", s++ + 3); return 0; }

Difficulty: Easy

Correct Answer: ce

Explanation:


Introduction / Context:
This question checks your understanding of pointer arithmetic with C-strings and the behavior of the postfix increment operator on pointers. The expression s++ + 3 is subtle: the postfix form returns the original pointer value before incrementing, and then an additional offset is applied for the printed substring.


Given Data / Assumptions:

  • str = "peace" (characters p e a c e followed by the null terminator).
  • s initially points to the first character of str (the letter p).
  • The format specifier %s prints from the supplied address until the null terminator.


Concept / Approach:
For pointers, the postfix increment s++ yields the current value of s, then increases s by 1 afterward. Adding an integer to a char advances by that many characters. Thus s++ + 3 is the address s (before increment) plus 3 characters into the array, and only after that expression is evaluated does s advance by 1 (which does not affect the already formed argument to printf).


Step-by-Step Solution:
Original s → &str[0] (points to 'p').Compute argument: (s++ + 3) → (&str[0] + 3) → &str[3] (points to 'c'5).The string starting at index 3 is "ce".After evaluating the argument, s becomes &str[1], but that no longer changes the already passed argument.


Verification / Alternative check:
Index the string directly: str + 3 points to the substring beginning with the fourth character (0-based indexing), which is indeed "ce".


Why Other Options Are Wrong:
"peace", "eace", and "ace" correspond to starting positions 0, 1, and 2, not 3. Therefore they are not printed by the given expression.


Common Pitfalls:
Misinterpreting postfix versus prefix increment and assuming the +3 applies after s moves. Here the original value is used for +3.


Final Answer:
ce

More Questions from Pointers

Discussion & Comments

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