Optarg 始终为空

Optarg is alway null

Optarg 始终为空。应用程序崩溃。

static const char* const short_options = "a:h:p";
static const struct option long_options[] =
{
    { "address",    1, NULL, 'a' },
    { "help",       0, NULL, 'h' },
    { "port",       1, NULL, 'p' }
};

我试图将空字符串添加到 long_options,但没有帮助。

static const struct option long_options[] =
{
    { "address",    1, NULL, 'a' },
    { "help",       0, NULL, 'h' },
    { "port",       1, NULL, 'p' },
    {0,             0, NULL,  0 }
};

但这并没有帮助。

There 是使用 optarg 的示例。我以相同的方式使用 optarg,但得到 null。

do {
        nextOption = getopt_long(argc, argv, short_options, long_options, NULL);
        switch (nextOption)
        {
        case 'a':
        {
            //do something
        }
            break;
        case 'h':
            printf(usage_template);
            exit(0);
        case 'p':
        {
            long value;
            char* end;
            value = strtol(optarg, &end, 10);//OPTARG IS NULL
            if (*end != '[=12=]')
            {
                printf(usage_template);
            }
            port = (uint16_t)htons(value);
        }
            break;
        case '?':
            printf(usage_template);
            exit(0);
        case -1:
            break;
        default:
            exit(0);
        }
    } while (nextOption != -1);

谁能帮我解决这个问题?

您的 "p" 选项后面似乎没有冒号,因此 getopt 不希望它有参数。