方法一:
//输入任意个字符串
#include
#include
#include
#define LINE 5
int main()
{
int i = 0, n = LINE;
int l, len;
char **str;
char buf[256]; //每个字符串256个字符够吗?
//分配原始内存大小
if (NULL == (str =(char **)malloc(sizeof(char*)*n)))
{
fprintf(stderr, "can not malloc(%d*%d)\n", sizeof(char*), n);
return 1;
}
printf("请输入字符串:(字符串间换行,两个换行结束输入)\n");
while (1)
{
//输入字符串
fgets(buf, 100, stdin);
if ('\n' == buf[0]) break; //读入空行,结束
//内存已满,扩充
if (i == n)
{
n += LINE;
if (NULL == (str =(char **) 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] =(char *)malloc(len - 1)))
{
fprintf(stderr, "can not malloc(%d)\n", len - 1);
return 1;
}
strcpy(str[i], buf);
i++;
}
//打印
printf("\n 你输入的字符串是:\n");
for (l = 0; l < i; l++)
printf("%s\n", str[l]);
system("pause");
return 0;
}
方法二:
#include
#include
#include
#include
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
printf("%u:%s\n",i+1,strs[i]);
free(strs);
free(str);
return 0;
}
温馨提示:答案为网友推荐,仅供参考