In C command-line arguments, the program below prints argv[argc - 1]. If it is executed as: cmd> sample (where argv[0] numerically refers to "sample"), what will it print? #include<stdio.h> int main(int argc, char **argv) { printf("%s\n", argv[argc-1]); return 0; }

Difficulty: Easy

Correct Answer: sample

Explanation:


Introduction / Context:
The item checks the layout of command-line arguments in C and how argc and argv relate. Specifically, argv[0] conventionally stores the program name (or path), and argc is the count of items in argv.


Given Data / Assumptions:

  • Program prints argv[argc - 1].
  • Program executed as: sample (no extra arguments).
  • argv[0] corresponds to "sample" under normal conventions.


Concept / Approach:
When the program is launched with no additional arguments, argc is 1 and argv points to an array of length 1 plus the terminating NULL. Therefore, argc - 1 equals 0, and the expression prints the string stored at argv[0], i.e., the program name path or name.


Step-by-Step Solution:

argc = 1 because there are no user arguments. argv[0] = "sample" (implementation may include a path, but the question assumes just the name). argv[argc - 1] = argv[0] = "sample".


Verification / Alternative check:
Add a second argument (e.g., sample X); now argc=2 and argv[argc - 1] = argv[1] = "X". The logic matches across cases.


Why Other Options Are Wrong:

  • 0, samp: Not the value at argv[0].
  • No output: The program prints a line; it does not exit silently.
  • Undefined behavior: Index is valid when argc > 0.


Common Pitfalls:
Forgetting that argv[0] is occupied by the program name; users sometimes assume argv[0] is the first user argument, which is incorrect.


Final Answer:
sample

More Questions from Command Line Arguments

Discussion & Comments

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