为什么在C中将argv(参数向量)定义为指针,以及将其第零定义为程序名称的需求是什么? [英] Why is argv (argument vector) in C defined as a pointer and what is the need for defining its zeroth as the program name?

查看:78
本文介绍了为什么在C中将argv(参数向量)定义为指针,以及将其第零定义为程序名称的需求是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
int main(int argc, char *argv[])
{
 int i;
 for(i=1;i<argc;i++)
  printf("%s%s", argv[i], (i<argc-1)? " ":"");
 printf("\n");
 return 0;
} 

上面给出的是一个简单的C程序,它输出命令行输入.此处argc是参数计数器.据说argv是一个包含参数的数组.我的问题是:为什么将它定义为指向字符数组而不是普通数组的指针?还需要将其第零个元素(argv [0])定义为调用程序的名称.

Given above is a simple C program that outputs command line inputs. Here argc is the argument counter. argv is said to be an array that contains arguments. My question is: why does it define as a pointer to a character array instead of a normal array? Also what is the need for defining its zeroth element (argv[0]) as the name by which the program is invoked.

我是初学者,请从高角度解释它.

I am a beginner and please explain it high level perspective.

推荐答案

char *argv[]char *数组衰减到的指针.例如,调用如下命令:

The char *argv[] is a pointer that an array of char * has decayed into. For example, invoking a command like this:

$ ./command --option1 -opt2 input_file

可以被视为:

char *argv[] = {
    "./command",
    "--option1",
    "-opt2",
    "input_file",
    NULL,
};
main(4, argv);

因此,基本上在main之外有一个字符串数组,它在main中传递给您:

So basically there is an array of strings outside main, and it is passed to you in main:

    char *argv[]
    \- --/     ^
      V        |
      |   It was an array
      |
of strings


关于argv[0]是调用命令,其原因很大程度上是历史原因.我不知道第一个想到它的人是怎么想的,但是我至少可以说出它的一个有用之处.


Regarding argv[0] being the invocation command, the reason is largely historical. I don't know what the first person who thought of it thought about, but I can tell at least one usefulness for it.

想象一个程序,例如vimgawk.这些程序可能会安装指向同一程序的符号链接(例如viawk).因此,有效地运行vimvi(或类似的gawkawk)可以执行完全相同的程序.但是,通过检查argv[0],这些程序可以告诉您它们是如何被调用的,并可能相应地进行调整.

Imagine a program, such as vim or gawk. These programs may install symbolic links (such as vi or awk) which point to the same program. So effectively, running vim or vi (or similarly gawk or awk) could execute the exact same program. However, by inspecting argv[0], these programs can tell how they have been called and possibly adjust accordingly.

据我所知,我上面提到的两个程序都没有做到这一点,但是它们可以做到.例如,通过名为vi的符号链接调用的vim可能会打开某些兼容性.或者称为awkgawk可以关闭某些GNU扩展.在现代世界中,如果他们想这样做,他们可能会创建提供正确选项的脚本.

As far as I know, neither of the programs I mentioned above actually do this, but they could. For example vim called through a symbolic link named vi could turn on some compatibility. Or gawk called as awk could turn off some GNU extensions. In the modern world, if they wanted to do this, they would probably create scripts that gives the correct options, though.

这篇关于为什么在C中将argv(参数向量)定义为指针,以及将其第零定义为程序名称的需求是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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