Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
862 views
in Technique[技术] by (71.8m points)

unix - Assigning optarg to an int in C

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);

  return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", 
                 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...