手机版
你好,游客 登录 注册
背景:
阅读新闻

C语言中给main函数传递参数

[日期:2014-08-16] 来源:Linux社区  作者:dcx1205 [字体: ]

相信大家用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!
 
大家可以利用这个程序模型干很多事呢!

C++ Primer Plus 第6版 中文版 清晰有书签PDF+源代码 http://www.linuxidc.com/Linux/2014-05/101227.htm

读C++ Primer 之构造函数陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm

读C++ Primer 之智能指针 http://www.linuxidc.com/Linux/2011-08/40177.htm

读C++ Primer 之句柄类 http://www.linuxidc.com/Linux/2011-08/40175.htm

将C语言梳理一下,分布在以下10个章节中:

  1. Linux-C成长之路(一):Linux下C编程概要 http://www.linuxidc.com/Linux/2014-05/101242.htm
  2. Linux-C成长之路(二):基本数据类型 http://www.linuxidc.com/Linux/2014-05/101242p2.htm
  3. Linux-C成长之路(三):基本IO函数操作 http://www.linuxidc.com/Linux/2014-05/101242p3.htm
  4. Linux-C成长之路(四):运算符 http://www.linuxidc.com/Linux/2014-05/101242p4.htm
  5. Linux-C成长之路(五):控制流 http://www.linuxidc.com/Linux/2014-05/101242p5.htm
  6. Linux-C成长之路(六):函数要义 http://www.linuxidc.com/Linux/2014-05/101242p6.htm
  7. Linux-C成长之路(七):数组与指针 http://www.linuxidc.com/Linux/2014-05/101242p7.htm
  8. Linux-C成长之路(八):存储类,动态内存 http://www.linuxidc.com/Linux/2014-05/101242p8.htm
  9. Linux-C成长之路(九):复合数据类型 http://www.linuxidc.com/Linux/2014-05/101242p9.htm
  10. Linux-C成长之路(十):其他高级议题

本文永久更新链接地址http://www.linuxidc.com/Linux/2014-08/105636.htm

linux
相关资讯       main函数  C语言函数  C语言main函数参数 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款