Bootstrap

字符型指针数组变量 c语言,怎么用指针数组接收输入的任意个字符串

如何用指针数组接收输入的任意个字符串

如何用指针数组接收输入的任意个字符串,我想用指针数组保存输入n个字符串变量,以便接下来的操作。在线等。。。。

------解决思路----------------------

这样可好:

#include 

#include 

#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 

return 0;

}

//111111

//222222

//3333333

//44444444

//555555555

//zhangxiang

//David

//

//111111

//222222

//3333333

//44444444

//555555555

//zhangxiang

//David

------解决思路----------------------

#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;

}

;