概述
我们都知道C语言和C++中程序的开始都是从main函数开始的,那么main函数也是一个函数,也有返回值和形参,返回值返回给系统,那么形参又是怎么传入的呢。参照普通函数的调用方法,在调用时传入参数,那么也就是说在使用main函数时候传入参数,实际上就是在命令行中执行程序时带参数。
具体步骤演示
1.程序
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
//argument count变元计数-->argc
//argument value变元值-->argv字符数组
//atoi将字符转换成整数
//argv数组中0索引表示当前执行程序,1开始表示传入的参数,参数之间以空格隔开
int main(int argc, char* argv[])
{
int a, b;
a = atoi(argv[1]);
b = atoi(argv[2]);
printf("%d,%d\n", a, b);
return 0;
}
2.执行程序
①在vs studio2019中直接执行会报空指针异常,因为没有参数传入。
②在windows命令行中执行
③在Linux系统中编译执行
test.c文件
[zsh@localhost test2]$ vi test.c
[zsh@localhost test2]$ gcc test.c -o test.out
[zsh@localhost test2]$ ./test.out 100 110 120
110 110 120
[zsh@localhost test2]$