【Linux】
main函数原型如下:
main( int argc, char *argv[ ], char *envp[ ] ) |
可知,main函数是有参数的,
第一个参数:argc是一个整形变量,表示命令行参数的个数(含第一个参数,即目录)
例如在Linux下 ./a.out -a -b -c -4... 这一段命令由多少个空格隔开多少个区域,argc就是几,在此是argc = 5;
第二个参数(char *argv[ ]):argv是一个字符指针的数组,即它里面的所有元素都是字符指针,指向字符串,也就是argv[]里面的所以元素都是字符串,这些字符串就是命令行中每一个参数;里面有argv+1个有效元素,最后一个元素为NULL。
第三个参数:envp是字符指针的数组,数组的每一个元素是一个指向一个环境变量(字符串)的字符指针。
想要看envp如下代码:
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> #include<string.h> int main(int argc, char *argv[],char *envp[]) { int i = 0; for (i = 0; envp[i]; i++) { printf("envp[%d]->%s\n", i, envp[i]); } system("pause"); return 0; }
假设我们输入以下代码(Linux):
#include<stdio.h> #include<stdlib.h> int main(int argc,char *argv[]) { int i = 0; for(i = 0; i < argc; i++) { printf("%d->%s\n",i,argv[i]); } system("pause"); return 0; }
输出结果如下:
[root@localhost class_3]# ./a.out -a -b -c
0->./a.out
1->-a
2->-b
3->-c
【参数列表应用】
#include<stdio.h> #include<stdlib.h> int main(int argc,char *argv[]) { int i = 0; if(argc == 1) return -1; if(strcmp(argv[1],"-a") == 0) printf("hello world!\n"); else if(strcmp(argv[1],"-b") == 0) printf("hello linux!\n"); else if(strcmp(argv[1],"-c") == 0) printf("hello haha!\n"); else printf("default!\n"); system("pause"); return 0; }
输出结果:
[root@localhost class_3]# ./a.out
[root@localhost class_3]# ./a.out -a
hello world!
[root@localhost class_3]# ./a.out -b
hello linux!
[root@localhost class_3]# ./a.out -c
hello haha!
[root@localhost class_3]# ./a.out -v
default!
【Windows】
选中项目——属性——调试——命令参数(添加命令)
效果和上述一样;