Home > Back-end >  How to check command line arugment match? (C)
How to check command line arugment match? (C)

Time:09-30

int main( int argc, char **argv ) {

 }

In this specific program, I want to check the whether the length of the char **argv is match to the argument count. However, I am not sure how I can loop through the character array of pointer of pointer.

Can anyone give me a suggestion? I am very new to C from Java base.

CodePudding user response:

The C standard is pretty self-explanatory in this case. Relevant parts from C17 5.1.2.2.1:

  • argv[argc] shall be a null pointer.
  • If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, ...
  • If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters.

You don't need to check if your compiler fulfils the above requirements unless you have reason to believe it is non-conforming, in which case all bets of program behavior are off anyway.

CodePudding user response:

Like this:

#include <stdio.h>

int main( int argc, char **argv )
{
    int n_argv=0;

    while(*argv  !=NULL) n_argv  ;

    printf("argc: %d  n_argv: %d", argc, n_argv);

    return 0;
}
  •  Tags:  
  • c
  • Related