为什么 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?
问题描述
#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.
推荐答案
argv
被定义为指针而不是数组,因为 C 中没有数组参数这样的东西.
argv
is defined as a pointer rather than as an array because there is no such thing as an array parameter in C.
argv
>
您可以定义一些看起来像数组参数的东西,但它在编译时调整"为数组类型;例如,这两个声明完全等效:
You can define something that looks like an array parameter, but it's "adjusted" to array type at compile time; for example, these two declarations are exactly equivalent:
int foo(int param[]);
int foo(int param[42]); /* the 42 is quietly ignored */
int foo(int *param); /* this is what the above two declarations really mean */
而main
的定义可以写成:
int main(int argc, char *argv[]) { /* ... */ }
或作为
int main(int argc, char **argv) { /* ... */ }
两者完全相同(第二个,恕我直言,更清楚地表达了实际情况).
The two are exactly equivalent (and the second one, IMHO, more clearly expresses what's actually going on).
从某种意义上说,数组类型是 C 中的二等类型.操作数组的代码几乎总是通过指向元素的指针进行操作,执行指针算术以遍历元素.
Array types are, in a sense, second-class types in C. Code that manipulates array almost always does so via pointers to the elements, performing pointer arithmetic to traverse the elements.
comp.lang.c FAQ 的第 6 节解释了数组和指针之间经常令人困惑的关系.
Section 6 of the comp.lang.c FAQ explains the often confusing relationship between arrays and pointers.
(如果你被告知数组是真正的"指针,那么它们不是;数组和指针是不同的东西.)
(And if you've been told that arrays are "really" pointers, they're not; arrays and pointers are distinct things.)
至于为什么argv[0]
指向程序名,那只是因为它有用.一些程序在错误消息中打印他们的名字;其他人可能会根据调用它们的名称来改变它们的行为.将程序名称与命令行参数捆绑在一起是一个相当随意的选择,但它很方便且有效.
As for why argv[0]
points to the program name, that's just because it's useful. Some programs print their names in error messages; others may change their behavior depending on the name by which they're invoked. Bundling the program name with the command-line arguments was a fairly arbitrary choice, but it's convenient and it works.
这篇关于为什么 C 中的 argv(参数向量)定义为指针,并且需要将其第零个定义为程序名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!