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

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

问题描述

在我目前正在学习的数据结构课程中,我们的任务是用 C++ 编写一个网络爬虫.为了给我们一个良好的开端,教授为我们提供了一个程序来从给定的 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] 中的开关填充,而 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.

所以我转向你.最终的 if 块检查究竟是什么?

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天全站免登陆