Pointer to argument string and prefix increment: what character is printed?\n\n/* myprog.c /\n#include <stdio.h>\n\nint main(int argc, char argv[])\n{\n / Invoked as: myprog friday tuesday sunday /\n printf("%c", ++argv[1]);\n return 0;\n}\n

Difficulty: Medium

Correct Answer: r

Explanation:


Introduction / Context:
This program tests understanding of operator precedence and pointer arithmetic on C strings in argv. Specifically, it uses prefix ++ on a char (argv[1]) and then dereferences to print a single character.


Given Data / Assumptions:

  • argv[1] points to the string literal "friday".
  • The expression is ++argv[1].
  • Operator precedence: [] binds first, so ++ applies to the result of argv[1] (a char), not to argv itself.


Concept / Approach:
argv[1] is a char. Applying prefix ++ to a char moves it to the next character in the same string. After ++, the pointer points to the second character. Dereferencing with * yields that character.


Step-by-Step Solution:

Initial: argv[1] → "friday" (points at 'f').++argv[1] → pointer now points at 'r'.*++argv[1] → dereference → 'r'.


Verification / Alternative check:
Rewriting as char *p = argv[1]; ++p; putchar(*p); confirms the same result.


Why Other Options Are Wrong:

  • f: That would be *argv[1] without increment.
  • m or y: Characters from other strings or positions, not referenced by this expression.


Common Pitfalls:
Misreading ++argv[1] as ++argv then [1]; forgetting [] binds tighter than ++; confusing pre-increment with post-increment.


Final Answer:
r

More Questions from Command Line Arguments

Discussion & Comments

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