2016-09-22 91 views
-1

每當我嘗試調用-u ex時,都會收到此錯誤。 「./Randoms -u 100」這段代碼有什麼問題?分段錯誤:11

其他所有情況都可以正常工作。爲什麼會發生?我如何解決它?

我正試圖在下限-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 %c\n",c); 
      } else if (c == ':') { 
       c = optopt; 
       printf("missing value for option %c\n",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("%d\n", randomnumber); 
        nums--; 
     } 
c = 0; 
return 0; 

} 
+0

你發現了什麼,當你調試呢?它在哪裏崩潰?你在選項中不需要'u:'嗎? – John3136

+0

花了4個多小時,因此錯過了該死的冒號。公里。謝謝! –

+0

抱歉沒有看到這個問題已經解決了。 – clockley1

回答

1

更換

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

通過

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