Chinaunix首页 | 论坛 | 博客
  • 博客访问: 109902
  • 博文数量: 50
  • 博客积分: 968
  • 博客等级: 少尉
  • 技术积分: 492
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-17 09:51
文章分类

全部博文(50)

文章存档

2012年(2)

2011年(48)

我的朋友

分类: C/C++

2011-05-19 14:40:13


  1. /*
  2.    程序实现功能:从控制台获取一串字符串(含空格),将带有空格的字符串分割,保存到cmd字符串数组中
  3.    知识点:指向指针的指针实现传参,数组传参,数组指针的内存分配。
  4.  */
  5. #include <stdio.h>
  6. #include <malloc.h>
  7. #include <string.h>
  1. void get_cmd(char **p);
  2. int split_string(char *s,char _cmd[][100]);
  3. void print_array(char _arr[][100],int _len);
  4.     
  5. int main()
  6. {
  7.     char *s;
  8.     char (*cmd)[100];
  9.     int len;
  10.     s = (char *)malloc(sizeof(char)*100);
  11.     cmd = (char (*)[])malloc(sizeof(s));
  12.     /*注意不能用get_cmd(s),因为p存放的不是“s存放的地址”,而是
  13.      s本身的地址。详细查看“彻底搞定C指针”的第4篇。
  14.     */
  15.     get_cmd(&s);
  16.     len = split_string(s,cmd);
  17.     print_array(cmd,len);
  18. }
  19. /*可以用一个指针实现,这里只是演示指向指针的指针传参*/
  20. void get_cmd(char **p)
  21. {
  22.     fgets(*p,100,stdin);
  23. }

  24. /*将带有空格的字符串s进行解析,存放到cmd字符数组中*/

  25. int split_string(char *s,char _cmd[][100])
  26. {
  27.     char *p = s;
  28.     int i = 0;
  29.     int j = 0;
  30.     while(*p != '\n')
  31.     {
  32.         if(*p == ' ')
  33.         {
  34.             _cmd[i][j]='\0';
  35.             i++;
  36.             j = 0;
  37.             p++;
  38.             /*处理多个空格的情况*/
  39.             while(*p == ' ')
  40.             {
  41.                 p++;
  42.             }
  43.         }
  44.         else
  45.         {
  46.             _cmd[i][j] = *p;
  47.             p++;
  48.             j++;
  49.         }
  50.     }
  51.     return i+1;
  52. }

  53. /*输出数组*/

  54. void print_array(char _arr[][100],int _len)
  55. {
  56.     int i = 0;
  57.     for(i = 0; i < _len ; i++)
  58.     {
  59.         printf("%s\n",_arr[i]);
  60.     }
  61. }

阅读(4447) | 评论(0) | 转发(2) |
0

上一篇:让你不在害怕指针

下一篇:UDP模拟FTP程序

给主人留下些什么吧!~~