The arguments argc
and argv
of main
is used as a way to send arguments to a program, the possibly most familiar way is to use the good ol' terminal where a user could type cat file
. Here the word cat
is a program that takes a file and outputs it to standard output (stdout
).
该程序接收参数的数量argc
和参数向量argv
,在上面的argument c数量将是两个(程序名称算作第一个参数)并且argument vector 将包含 [cat
,file
,null]。而最后一个元素是空指针。
通常,你会这样写:
int // Specifies that type of variable the function returns.
// main() must return an integer
main ( int argc, char **argv ) {
// code
return 0; // Indicates that everything went well.
}
如果您的程序不需要任何参数,那么编写一个同样有效main
- 按以下方式运行:
int main() {
// code
return 0; // Zero indicates success, while any
// Non-Zero value indicates a failure/error
}
在C语言的早期版本中,没有int
before main
正如所暗示的那样。今天,这被认为是一个错误。
On POSIX-兼容系统(和Windows),可以使用第三个参数char **envp
其中包含程序向量env铁变量。参数列表的进一步变化main
函数存在,但我不会在这里详细说明它,因为它是非标准的。
另外,变量的命名是习俗并且没有实际意义。坚持这一点总是一个好主意,这样你就不会混淆其他人,但定义它同样有效main
as
int main(int c, char **v, char **e) {
// code
return 0;
}
对于第二个问题,有多种方法可以向程序发送参数。我建议你看看exec*()函数族这是POSIX-标准,但可能是easier只是使用system("command arg1 arg2")
,但是使用system()
通常不受欢迎,因为它不能保证在每个系统上都能工作。我自己没有测试过;但如果没有bash
,zsh
,或安装在 *NIX 系统上的其他 shell,system()
将失败。