Search code examples
cargumentscommand-line-argumentsprogram-entry-point

Can't figure out how to store command line arguments correctly


I need to store two command line arguments, but I can't figure out how to do so correctly. My code currently stores an int that isn't correct (if I set the second variable to nothing) and gives an error saying invalid initialization. I tried initializing name with strcpy and strcat but that didn't help either because I got different errors mostly relating to casting.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(int argcount, char *args[])
{
   int number = *args[1];
   char name[] = *args[2];


   printf("number is %d and name is %s\n", number, name);

   return 0;
}

Solution

  • Here is what your main function should look like:

    int main(int argcount, char **args)
    {
       int number = atoi(args[1]); // atoi() converts your string to an int
       char *name = args[2]; // Do not dereference twice, otherwise you get a char
    
    
       printf("number is %d and name is %s\n", number, name);
    
       return 0;
    }
    

    int number = *args[1]; is wrong because args[1] is your first argument, and *argv[1] (or argv[1][0]) is the first letter of your argument. Putting this in your number variable will actually result in the ASCII value of the first letter of your first parameter been stocked in number. This is absolutely not what you want.

    char name[] = *args[2]; isn't correct either because here, you are trying to get the first letter of your second parameter (*args[2], or args[2][0]), which is a type char and put it inside an array of char.

    You might also want to check how many arguments your program gets and if these arguments are well formatted, otherwise your program could crash!