C 中命令行参数 `argv` 的类型是什么? [英] What is the type of command-line argument `argv` in C?
问题描述
我正在阅读 C Primer Plus 中关于命令行参数 argv
的部分,但我很难理解这句话.
I'm reading a section from C Primer Plus about command-line argument argv
and I'm having difficulty understanding this sentence.
说的是,
程序将命令行字符串存储在内存中并存储指针数组中每个字符串的地址.这个地址数组存储在第二个参数中.按照惯例,这个指针指向指针被称为 argv
,用于参数值.
The program stores the command line strings in memory and stores the address of each string in an array of pointers. The address of this array is stored in the second argument. By convention, this pointer to pointers is called
argv
, for argument values .
这是否意味着命令行字符串作为指向char
数组的指针数组存储在内存中?
Does this mean that the command line strings are stored in memory as an array of pointers to array of char
?
推荐答案
直接引用C11
,章节§5.1.2.2.1/p2,程序启动,(强调我的)
Directly quoting from C11
, chapter §5.1.2.2.1/p2, program startup, (emphasis mine)
int main(int argc, char *argv[]) {/* ... */}
[...] 如果 argc
的值大于零,数组成员 argv[0]
到argv[argc-1]
inclusive 应包含指向字符串的指针, [...]
[...] If the value of argc
is greater than zero, the array members argv[0]
through
argv[argc-1]
inclusive shall contain pointers to strings, [...]
和
[...] 和 argv
数组指向的字符串 [...]
[...] and the strings pointed to by the
argv
array [...]
所以,基本上,argv
是指向字符串数组 note 的第一个元素的指针.这可以从替代形式、
So, basically, argv
is a pointer to the first element of an array of strings note. This can be made clearer from the alternative form,
int main(int argc, char **argv) {/* ... */}
您可以将其重新表述为指向以空字符结尾的 char
数组的第一个元素的指针数组的第一个元素的指针,但我更愿意坚持使用字符串.
You can rephrase that as pointer to the first element of an array of pointers to the first element of null-terminated char
arrays, but I'd prefer to stick to strings .
注意:
在上面的答案中阐明指向数组第一个元素的指针"的用法,遵循§6.3.2.1/p3
To clarify the usage of "pointer to the first element of an array" in above answer, following §6.3.2.1/p3
除非它是 sizeof
运算符、_Alignof
运算符或一元 &
运算符,或者是用于初始化数组的字符串文字,具有type ''array of type'' 被转换为一个类型为 ''pointer to type'' 的表达式,它指向到数组对象的初始元素 并且不是左值.[...]
Except when it is the operand of the
sizeof
operator, the_Alignof
operator, or the unary&
operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. [...]
这篇关于C 中命令行参数 `argv` 的类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!