char * argv []如何在c/c ++中工作? [英] how does char* argv[] work in c/c++?
问题描述
我知道它用于从命令行使用参数,但是我没有得到声明.char * argv []?这是否意味着指向char数组的指针,如果是,为什么没有大小呢?如果它不是动态数组,就不必具有大小吗?
I know it is used to use arguments from the command line, I don't get the declaration though. char* argv[]? does it mean a pointer to a char array, if so why no size? don't you have to have a size if it's not a dynamic array?
我做了一些研究,发现有人说它会分解为char ** argv.这种腐烂的东西是如何工作的?
I have done a bit of research and come across people saying it decays to char **argv. how does this decay thing work?
感谢您的帮助-非常抱歉,您是菜鸟xD
Thanks for your help - sorry for being a noob xD
推荐答案
查看 argv
的最好方法是将其作为指向字符/字符串的指针的数组.每个 argv [i]
都指向一个字符,该字符是一个以空字符结尾的字符串的开头.
The best way to look at argv
is as an array of pointers to characters/strings. Each argv[i]
points to a character which is the start of a null-terminated string.
您传递了 argc
来告诉您数组中有多少个条目,但这在技术上是多余的,因为 argv [argc] == NULL
,所以您有两个检测参数列表结尾的方法.
You are passed argc
to tell you how many entries are in the array, but this is technically redundant since argv[argc] == NULL
, so you have two ways of detecting the end of the argument list.
衰减事物"是当您将数组传递给函数时,将其视为指向数组第一个元素的指针.
The decay 'thing' is that when you pass an array to a function, it is treated as a pointer to the first element of the array.
因此,如果将 int a [10]
传递给函数,则该值为& a [0]
且为 int * 代码>.在函数声明或定义中,可以互换地编写
int * x
或 int x []
.此元素与 argv
之间的唯一区别是元素类型不是 int
而是 char *
,因此 char * argv []
和 char ** argv
在函数的声明或定义中是等效的.请注意,此等价不适用于局部变量或全局变量. extern char ** v;
和 extern char * a [];
之间存在主要区别.
Thus, if you pass int a[10]
to a function, the value is &a[0]
and is an int *
. In the function declaration or definition, you can write int *x
or int x[]
interchangeably. The only difference between this and argv
is that the element type is not int
but char *
, so char *argv[]
and char **argv
are equivalent in the declaration or definition of a function. Note that this equivalence does not apply to either local or global variables. There are major differences between extern char **v;
and extern char *a[];
.
这篇关于char * argv []如何在c/c ++中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!