0

例として、次の関数を実装したいと思います。-a NUM] < 文字列 >

私のアプローチは次のとおりです。

int opt;
int opt_s = -1, opt_a = -1, num;
char *optstr ="<not yet set>";
num = -1;

if( argc < 3 || argc > 4 ) {
    fprintf(stderr, "Wrong number of arguments");
    usage();
}

/* Options */
while ((opt = getopt(argc, argv, "sa:")) != -1) {
    switch (opt) {
    case 's': {
        if (opt_s != -1) {
            fprintf(stderr, "opt_s multiple times\n");
            usage();         /* does not return */
        }
        else if (opt_a != -1) {
            fprintf(stderr, "Please only choose one option\n");
            usage();
        }
        else {
            ++opt_s;
            break;
        }
    }
    case 'a': {
        if (opt_a != -1) {
            fprintf(stderr, "opt_a multiple times\n");
            usage();        /* does not return */
        }
        else if (opt_s != -1) {
            fprintf(stderr, "Please only choose one option\n");
            usage();
        }
            ++opt_a;
            ++num; 
            break;
        }
    case '?': {
        usage();
        break;
    }
    // Impossible
    default: {
        assert(0);
    }
    }
}

/* Arguments */
if( num > -1 ) {
    if( (argc - optind) != 2 ) {
        usage();
    }
    num = (int)strtol( argv[optind], NULL, 0 );
    *optstr = argv[optind+1];
}
else {
    if( (argc - optind) != 1 ) {
        usage();
    }
    *optstr = argv[optind];
}

このコードには、機能しないことがいくつかあります。その理由と、これを行う正しい方法を知りたいです。

  • まず、getopt は引数を解析しようとして、? に入ります。場合
  • (optind - argc) は正しい数の引数をスローしません
  • argv[optind] を optstr に代入すると、次がスローされます。

    warning: assignment makes integer from pointer without a cast

すべての回答に事前に感謝します

4

1 に答える 1

1

3番目の質問の答えthe assignment of argv[optind] to optstr throws: warning ?は次のとおりです。

char *optstr; 
*optstr = argv[optind]; // Wrong if LHS is a string rather a char


optstr = argv[optind]; // Correct one

ここでoptstrは、単一の文字または文字列を格納できる文字へのポインターです。また、RHSは文字列を*optstr参照し、ポインタを参照します。したがって、警告。charargv[optind]

于 2013-11-13T18:56:55.967 に答える