LearnFrenzy
Sign in Take a free test

Command Line Arguments · Find the Error · Question 6

Bug: counting arguments with sizeof(argv) Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What does this program print when run as shown, and why?

Run as: ./app a b c

main.c
#include <stdio.h>

int main(int argc, char *argv[]) {
    (void) argc;
    size_t n = sizeof(argv) / sizeof(argv[0]);
    printf("%zu arguments\n", n);
    return 0;
}
  • A 3 arguments
  • B 1 arguments – argv is really a char ** parameter, so sizeof gives 8 / 8; use argc Correct
  • C 4 arguments
  • D It does not compile
Correct Answer: Option B

Array parameters are pointers, so the sizeof trick only measures a pointer. That is exactly why main receives argc. Compilers warn: "sizeof on array function parameter will return size of char **".

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links