Why check if (*argv == NULL)? [duplicate]

点点圈 提交于 2019-12-05 00:40:24

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
}

3.6.1/2:

If argc is non-zero those arguments shall be provided in argv[0] though ... and argv[0] shall be the pointer to the initial character of a NTMBS that represents the name used to invoke the program or "". The value of argc shall be nonnegative. The value of argv[argc] shall be 0.

Emphasis mine. argc is only guaranteed non-negative, not non-zero.

This is at entry to main. It's also possible that //do stuff modifies the value of argv, or the contents of the array it points to. It's not entirely unheard of for option-handling code to shift values off argv as it processes them. The test for *argv == null may therefore be testing whether or not there are any command-line arguments left, after the options have been removed or skipped over. You'd have to look at the rest of the code.

Remembering just how portable C is, it might not always be running on a standard platform like Windows or Unix. Perhaps it's some micro-code inside your washing machine running on some cheap, hacked environment. As such, it's good practice to make sure a pointer isn't null before dereferencing it, which might have led to the question.

Even so, you're correct. *argv is the same as argv[0], and argv is supposed to be initialized by the environment, if it's provided.

just a speculation.

what if your professor is referring to this ??

while(*++argv !=NULL)

    printf("%s\n",*argv);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!