吾爱吃豆豆

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

指针数组接收字符串

 1 /*功能:用指针数组接收输入的n组字符串*/ 
 2 /*宏LINE是初始字符串个数以及每次分配的内存不够时重新realloc的增量*/ 
 3 #include <stdio.h>
 4 #include <string.h>
 5 #include <stdlib.h>
 6 #define LINE 5
 7 int i = 0,n,m = LINE;
 8 int l, len;
 9 char **str;
10 char buf[100];    //每个字符串100个字符够吗?
11 int main()
12 
13 {
14 
15     printf("请输入要输入的字符串数n:");
16     n=atoi(fgets(&n,256,stdin));
17     //scanf("%d",&n);
18     //fflush(stdin);//因为字符串最后的回车符也会被scanf接收,从而残留在缓冲区内。 
19 //        printf("n的值为:%d\n",n);
20 
21     //分配原始内存大小
22 
23     if (NULL == (str = malloc(sizeof(char*)*n)))
24 
25     {
26         fprintf(stderr, "can not malloc(%d*%d)\n", sizeof(char*), n);
27         return 1;
28     }
29 //    while (1)
30     for(i;i<n;i++)
31     {
32 
33         fgets(buf, 100, stdin);
34         if ('\n' == buf[0]) break;     //读入空行,结束
35         //内存已满,扩充
36         if (i == n)
37         {
38 
39             n += LINE;
40 
41             if (NULL == (str = realloc(str, sizeof(char*)*n)))
42 
43             {
44 
45                 fprintf(stderr, "can not realloc(%d*%d)\n", sizeof(char*), n);
46                 return 1;
47 
48             }
49         }
50 
51         len = strlen(buf);
52 
53         buf[len - 1] = 0;  //去'\n'
54         if (NULL == (str[i] = malloc(len - 1)))
55         {
56             fprintf(stderr, "can not malloc(%d)\n", len - 1);
57             return 1;
58         }
59 
60         strcpy(str[i], buf);
61 
62     //    i++;
63     }
64     //打印
65     for (l = 0; l < i; l++) printf("%s\n", str[l]);
66     return 0;
67 
68 }

 

posted on 2015-06-16 13:51  吾爱吃豆豆  阅读(307)  评论(0)    收藏  举报