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;
}
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With