设为首页 加入收藏

TOP

C语言中给main函数传递参数
2014-11-23 21:36:06 】 浏览:4556
Tags:言中 main 函数 传递 参数

相信大家用C语言定义main函数时,大多数人的写法都是int main(void)。其实main函数是可以向其传递参数的,给个实例:


//给main函数传参实例:

#include
#include

//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语言梳理一下,分布在以下10个章节中:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇详解realloc函数的功能——C语言.. 下一篇C语言中sizeof()求字节数的应用举..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目