简体   繁体   English

atoi命令中的分段错误

[英]Segmentation fault in atoi command

I have the following code: 我有以下代码:

int main(int argc, char *argv[])
{
    int value,direction=0;
    char c;
    printf ("go\n");
    while((c = getopt(argc, argv, "wr:")) != -1) {
        printf ("go\n");
        printf("%c\n",c);
        switch(c) {
        case 'w':
            printf ("go\n");
            value=atoi(optarg);
            printf ("go\n");
            printf("The input value is %x",value);
            direction=1; //1 for write
            break;
        case 'r':
            direction=0; // 0 for read
            break;
        default:
            printf("invalid option: %c\n", (char)c);
            usage();
            return -1;
        }

    }
}

Now when i run the program by writing 现在,当我通过编写来运行程序时

 ./spicode.out -w 25

I need to pick the 25 after w using optarg, but its producing a segmentation fault. 我需要在使用optarg的w之后选择25,但是它会产生分段错误。

What am i doing wrong? 我究竟做错了什么?

您应该在命令行选项之间放置冒号。

   c = getopt(argc, argv, "w:r")

From gnu.org : 来自gnu.org:

An option character in this string can be followed by a colon (':') to indicate that it takes a required argument 此字符串中的选项字符后可以跟一个冒号(':'),以表示它接受必需的参数

Therefore wr: becomes w:r 因此wr:变成w:r

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM