这个代码有什么问题?分段故障:11



每当我尝试调用-u ex时,都会出现此错误。"。/随机-u 100"

所有其他情况下工作正常。为什么会发生这种情况?我怎么修理它?

我正在尝试打印下界-l和上界之间的随机数- u。全部作为命令行参数发送。

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <ctype.h>
    #include <string.h>
    #include <time.h>
    static char *prgn;
    int main(int argc, char *argv[])
    {
       srand(time(NULL));
      int randomnumber;
      int nums = 10;  
      int l = 1;
      int u = 100; 
      int c = 0;
      int error = 0;
      char *options = ":n:l:u";
      prgn = (char *)malloc(sizeof(char)*(strlen(argv[0])+1));
      strcpy(prgn,argv[0]);
      while ((c = getopt(argc,argv,options)) != -1) {
            if (c == '?') {
               c = optopt;
               printf("illegal option %cn",c);
            } else if (c == ':') {
               c = optopt;
               printf("missing value for option %cn",c);
            }
            else {
         switch (c) {
            case 'n':
               nums =  atoi(optarg);
               break;
            case 'u':
               u = atoi(optarg);
            break; 
            case 'l':
               l = atoi(optarg);
            break;
         }
      }
   }
       while (nums !=0){
                  randomnumber = l + rand() % (u - l);
                  printf("%dn", randomnumber);
                  nums--;
         }
c = 0;
return 0;
}

Replace

char *options = ":n:l:u";

char *options = "n:l:u:";

最新更新