In C, argv points to the command-line argument vector. For the program below executed as: cmd> myprog one two three, what does the statement printf("%s
", *++argv); print?
/* myprog.c */
#include
#include
int main(int argc, char **argv)
{
printf("%s
", *++argv);
return 0;
}
-
Amyprog
-
Bone
-
Ctwo
-
Dthree
-
EUndefined behavior
Answer
Correct Answer: one
Explanation
Introduction / Context: This question probes pointer arithmetic with argv. The expression ++argv advances the pointer to the first user argument and then dereferences it to a char string.
Given Data / Assumptions:
- Command line: myprog one two three
- argv initially points at argv[0] (i.e., "myprog").
Concept / Approach: Pre-increment ++argv moves the argv pointer from &argv[0] to &argv[1]. Dereferencing with * yields argv[1], the first user argument string, "one".
Step-by-Step Solution:
Initial: argv[0] = "myprog", argv[1] = "one". *++argv -> increment to &argv[1], then dereference -> "one". printf prints "one".Verification / Alternative check: If you used printf("%s", argv[2]); you would get "two". The *++argv form is a compact idiom for skipping argv[0].
Why Other Options Are Wrong:
- myprog: That would be *argv before increment.
- two or three: Those are later elements, not the first after increment.
- Undefined behavior: This is well-defined with argc > 1.
Common Pitfalls: Confusing *argv++ with *++argv: post-increment returns the old pointer, pre-increment returns the incremented one; here pre-increment is used.
Final Answer: one