namarino namarino - 1 year ago 102
C Question

Printing integers from command line arguments in C

I'm running my program with some command line arguments. But when I enter 10, 10, 10 and print them out, it prints out 49, 49, 49. Here's my code:

int main(int argc, char *argv[]) {
int seed = *argv[0];
int arraySize = *argv[1];
int maxSize = *argv[2];

Why is this happening??

Answer Source

Well, argv is an array of pointer to strings. All command line arguments are passed as strings and the pointer to each of them is held by argv[n], where the sequence for the argument is n+1.

For a hosted environment, quoting C11, chapter ยง5.

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.

So, clearly, for an execution like

./123 10 10 10 //123 is the binary name

  • argv[0] is not the first "command line argument passed to the program". It's argv[1].
  • *argv[1] does not return the int value you passed as the command-line argument.

    Basically, *argv[1] gives you the value of the first element of that string (i.e, a char value of '1'), most possibly in ASCII encoded value (which you platform uses), ansd according to the ascii table a '1' has the decimal va;lue of 49, which you see.

Solution: You need to

  • Check for the number of arguments (argc)
  • Loop over each argument string argv[1] ~ argv[n-1] while argc == n
  • Convert each of the input string to int (for this case, you can make use of strtol())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download