C语言中给main函数传递参数!
2014-04-14 16:54
393 查看
相信大家用C语言定义main函数时,大多数人的写法都是int main(void)。其实main函数是可以向其传递参数的,给个实例:
//给main函数传参实例:
#include <stdio.h>
#include <string.h>
//int main(int argc, char *argv[])
int main(int argc, char **argv)
{
char *array[3] = {"./main", "hello", "world"};
if (argc < 2)
{
printf("error!\n");
printf("./main str\n");
return -1;
}
printf("The first string of your command is:%s\n", argv[0]);
printf("The second string of your command is:%s\n", argv[1]);
printf("The third string of your command is:%s\n", argv[2]);
if (!strcmp(argv[0], array[0]))
{
printf("The first command execute successfully!\n");
}
if (!strcmp(argv[1], array[1]))
{
printf("The second command execute successfully!\n");
}
if (!strcmp(argv[2], array[2]))
{
printf("The third command execute successfully!\n");
}
return 0;
}
输出结果:
(1)若输入命令为:./main
则输出结果为:
error!
The command is:./main
(2)若输入命令为:./main hello world
则输出结果为:
The first string of your command is:./main
The second string of your command is:hello
The third string of your command is:world
The first command execute successfully!
The second command execute successfully!
The third command execute successfully!
大家可以利用这个程序模型干很多事呢!
//给main函数传参实例:
#include <stdio.h>
#include <string.h>
//int main(int argc, char *argv[])
int main(int argc, char **argv)
{
char *array[3] = {"./main", "hello", "world"};
if (argc < 2)
{
printf("error!\n");
printf("./main str\n");
return -1;
}
printf("The first string of your command is:%s\n", argv[0]);
printf("The second string of your command is:%s\n", argv[1]);
printf("The third string of your command is:%s\n", argv[2]);
if (!strcmp(argv[0], array[0]))
{
printf("The first command execute successfully!\n");
}
if (!strcmp(argv[1], array[1]))
{
printf("The second command execute successfully!\n");
}
if (!strcmp(argv[2], array[2]))
{
printf("The third command execute successfully!\n");
}
return 0;
}
输出结果:
(1)若输入命令为:./main
则输出结果为:
error!
The command is:./main
(2)若输入命令为:./main hello world
则输出结果为:
The first string of your command is:./main
The second string of your command is:hello
The third string of your command is:world
The first command execute successfully!
The second command execute successfully!
The third command execute successfully!
大家可以利用这个程序模型干很多事呢!
相关文章推荐
- 给c语言main函数传递参数
- C语言中的参数传递机制详解
- C语言main函数的参数含义及输入
- C语言二维数组作为函数参数传递
- c语言main函数返回值、参数详解
- 函数传递不定参数理解-c语言
- C语言main函数带参数在VC6下的调试方法
- C语言和JAVA一样,函数参数传递方式都为值传递方式
- 转:C语言中如何将二维数组作为函数的参数传递
- main函数传递参数个数
- C++向main函数传递参数的方法(实例已上传至github)
- C语言中main函数的参数
- 关于C语言中函数调用和参数传递机制的探讨
- 关于C语言中函数调用和参数传递机制的探讨(二 .传递一个参数)
- 《C语言及程序设计》程序阅读——参数传递方式:传值与传地址
- c语言中main函数的参数int argc,char *argv[]
- C传递参数给main函数
- c语言的参数传递
- C语言中如何将二维数组作为函数的参数传递
- CodeBlocks下如何给main函数传递参数