为什么要检查(* argv == NULL)? [英] Why check if (*argv == NULL)?

查看:144
本文介绍了为什么要检查(* argv == NULL)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我目前正在学习的数据结构类中,我们的任务是用C ++编写Web搜寻器.为了让我们有一个良好的开端,这位教授为我们提供了一个程序,该程序可以从给定的URL获取源,还提供了一个简单的HTML解析器以将标签剥离.该程序的主要功能接受参数,因此使用argc/argv.用于检查参数的代码如下:

In the data structures class that I am currently taking, we have been tasked with writing a web crawler in C++. To give us a head start, the professor provided us with a program to get the source from a given URL and a simple HTML parser to strip the tags out. The main function for this program accepts arguments and so uses argc/argv. The code used to check for the arguments is as follows:

// Process the arguments
if (!strcmp(option, "-h"))
{
    // do stuff...
}
else if (!strcmp(option, ""))
{
    // do stuff...
}
else if (!strcmp(option, "-t"))
{
    // do stuff...
}
else if (!strcmp(option, "-a"))
{
    // do stuff...
}

if ( *argv == NULL )
{
    exit(1);
}

其中argv [1]中的开关已填充"option",而argv [2]及更高版本具有其余参数.我理解的第一个块就很好,如果开关等于字符串,则根据开关执行任何操作.我想知道最后一个if块的目的是什么.

Where "option" has been populated with the switch in argv[1], and argv[2] and higher has the remaining arguments. The first block I understand just fine, if the switch equals the string do whatever based on the switch. I'm wondering what the purpose of the last if block is though.

可能是我的C ++有点生锈,但是我似乎还记得* argv等效于argv [0],基本上意味着它正在检查以确保存在参数.除了给我的印象是argv [0]总是(至少在大多数实现中)包含正在运行的程序的名称.在我看来,如果argc等于0,则argv [0]可能为null,但是在Google上搜索时,我找不到一个单独的帖子来确定这是否可能.

It could be that my C++ is somewhat rusty, but I seem to recall *argv being equivalent to argv[0], basically meaning it is checking to make sure arguments exist. Except I was under the impression that argv[0] always (at least in most implementations) contained the name of the program being run. It occurs to me that argv[0] could be null if argc is equal to 0, but searching around on Google I couldn't find a single post determining whether or not that is even possible.

所以我转向你.如果进行了块检查,那么最终的结果到底是什么?

And so I turn to you. What exactly is that final if block checking?

编辑:我已经采用了所选答案的注释中提供的推理,即有可能有意使argv [0]变为NULL,否则可能基于以下原因变为NULL: main的特定于平台的实现.

I've gone with the reasoning provided in the comments of the selected answer, that it may be possible to intentionally cause argv[0] to become NULL, or otherwise become NULL based on an platform-specific implementation of main.

推荐答案

argc将为您提供传递的命令行参数数量.您也不必检查argv的内容,也可以查看是否没有足够的参数.

argc will provide you with the number of command line arguments passed. You shouldn't need to check the contents of argv too see if there are not enough arguments.

if (argc <= 1) { // The first arg will be the executable name
   // print usage
}

这篇关于为什么要检查(* argv == NULL)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆