怎么用指针数组接收输入的任意个字符串
如何用指针数组接收输入的任意个字符串
如何用指针数组接收输入的任意个字符串,我想用指针数组保存输入n个字符串变量,以便接下来的操作。在线等。。。。
------解决思路----------------------
这样可好:
------解决思路----------------------
如何用指针数组接收输入的任意个字符串,我想用指针数组保存输入n个字符串变量,以便接下来的操作。在线等。。。。
------解决思路----------------------
这样可好:
#include <stdio.h>
#include <string.h>
#define LINE 5
int i = 0, n = LINE;
int l, len;
char **str;
char buf[100]; //每个字符串100个字符够吗?
int main()
{
//分配原始内存大小
if (NULL == (str = malloc(sizeof(char*)*n)))
{
fprintf(stderr, "can not malloc(%d*%d)\n", sizeof(char*), n);
return 1;
}
while (1)
{
fgets(buf, 100, stdin);
if ('\n' == buf[0]) break; //读入空行,结束
//内存已满,扩充
if (i == n)
{
n += LINE;
if (NULL == (str = realloc(str, sizeof(char*)*n)))
{
fprintf(stderr, "can not realloc(%d*%d)\n", sizeof(char*), n);
return 1;
}
}
len = strlen(buf);
buf[len - 1] = 0; //去'\n'
if (NULL == (str[i] = malloc(len - 1)))
{
fprintf(stderr, "can not malloc(%d)\n", len - 1);
return 1;
}
strcpy(str[i], buf);
i++;
}
//打印
for (l = 0; l < i; l++) printf("%s\n", str[l]);
return 0;
}
//111111
//222222
//3333333
//44444444
//555555555
//zhangxiang
//David
//
//111111
//222222
//3333333
//44444444
//555555555
//zhangxiang
//David
------解决思路----------------------
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
int main()
{
char *str=NULL,**strs=NULL,*p;
unsigned int str_size=0,strs_size=0,i;
do
{
char *tmp=(char*)realloc(str,++str_size*sizeof(char));
if(!tmp)
{
free(str);
fputs("out of memory",stderr);
return 1;
}
str=tmp;
str[str_size-1]=getchar();
}while(str[str_size-1]!='\n');
str[str_size-1]=0;
for(p=strtok(str," \t");p;p=strtok(NULL," \t")) {
char **tmp=(char**)realloc(strs,++strs_size*sizeof(char*));
if(!tmp)
{
free(str);
free(strs);
fputs("out of memory",stderr);
return 1;
}
strs=tmp;
strs[strs_size-1]=p;
}
for(i=0;i<strs_size;++i)
printf("%u:%s\n",i+1,strs[i]);
free(strs);
free(str);
return 0;
}