简体   繁体   English

c optarg atoi没有参数

[英]c optarg atoi with no args

Consider the following code: 考虑以下代码:

int number;

while((w = getopt(argc, argv, "n:s:")) != -1) {

        switch (w){

            case 'n': {

                opfile->filename = optarg;

            }break;

            case 's': {

                number = atoi(optarg);

            }break;

        }
}

Now, when I leave both options or the option s blank, for example I start my program with no command line args, then the number variable still gets a random value. 现在,当我将两个选项或选项s都保留为空白时,例如,我在没有命令行参数的情况下启动程序,那么number变量仍将获得随机值。

What am I missing here? 我在这里想念什么? Some if-statement in the case of s ? 关于s一些if陈述? Specifically, I want to cover the case where the user doesn't assign a specific value/option to s in the command line arguments. 具体来说,我想介绍用户未在命令行参数中为分配特定值/选项s情况。

When there is no 's' option passed to the program, the case 's' branch is not executed at all, and nothing else sets number to a value, which means that subsequent reads trigger undefined behavior. 当没有“ s”选项传递给程序时, case 's'分支根本不会执行,其他都不会将number设置为值,这意味着后续的读取会触发未定义的行为。 (This is potentially much worse than just giving you a random value when you read from it later. It's a must-fix bug.) (这可能比以后读取时给您一个随机值要糟糕得多。这是一个必须修复的错误。)

But because nothing else touches number , it will be enough to change 但是,因为没有别的东西触及number ,所以改变就足够了

int number;

to

int number = 0;

or whatever else you want your default to be. 或其他任何您想要的默认值。

(By the way, you should really be using strtol instead of atoi , because atoi ignores syntax errors.) (顺便说一句,您确实应该使用strtol而不是atoi ,因为atoi忽略语法错误。)

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

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