Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning optarg to an int in C

Tags:

c

unix

casting

int

I am trying to assign an optarg value to an int, but the compiler gives me the following warning:

warning: assignment makes integer from pointer without a cast [enabled by default]

I have tried casting optarg as int before the assignment

n = (int) optarg;

but still get a warning:

warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]

I am not sure what needs to be done before I can simply assign the optarg to an integer, then print it (for now).

int main (int argc, char *argv[])
{
  char c;
  int n;

  while ((c = getopt(argc, argv, "m:")) != -1) {
    switch (c) {
    case 'm':
      n = optarg;
      break;
    }
  }

  printf("%d\n", n);

  return 0;
}
like image 429
Acroyear Avatar asked Dec 21 '22 05:12

Acroyear


2 Answers

The option string is always a string.

If you want an integer, you need to use a conversion function, like atoi(3)

So you should at least code

n = atoi(optarg);

Beware, optarg could be NULL and could certainly be a non-number. You might use strtol(3) which may set the ending character which you would check.

So a more serious approach could be

case 'm':
  {
     char* endp = NULL;
     long l = -1;
     if (!optarg ||  ((l=strtol(optarg, 0, &endp)),(endp && *endp)))
       { fprintf(stderr, "invalid m option %s - expecting a number\n", 
                 optarg?optarg:"");
         exit(EXIT_FAILURE);
       };
      // you could add more checks on l here...
      n = (int) l;
     break;
  }
  n = optarg;
  break;

Notice the assignment to l as expression and the comma operator inside the if test.

BTW, GNU Libc also have argp functions (and also getopt_long - but argp functions are more powerful), which you may find more convenient. Several frameworks (notably Gtk and Qt) have also program argument passing functionalities.

If you are doing a serious program please make it accept the --help option, and if possible the --version one. It is really convenient, and I hate the few programs which don't accept them. See what GNU standards say.

like image 73
Basile Starynkevitch Avatar answered Jan 02 '23 17:01

Basile Starynkevitch


optarg is a pointer to a string - if you want to convert that to an integer, the simplest way is with atoi:

case 'm':
    n = atoi(optarg);
    break;
like image 25
RichieHindle Avatar answered Jan 02 '23 19:01

RichieHindle