2019-01-14 回答
“任意长度”实际上是做不到的,即使所用的软件平台没有限制,硬件环境也不允许。所以“任意长度”应当理解为在一个很大的空间之内没有限制地输入字符串而不用事先确定长度。鉴于这种理解,可以定义一个输入函数,先动态申请一个较大的空间,直接向其内输入字符串;输入完毕后检测其长度,再按实际需要申请一个合适大小的空间,把刚才输入的字符串拷贝到这个合适大小的空间里,再把原先申请的大空间释放。举例代码如下:
//#include "stdafx.h"//if the vc++6.0, with this line.
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#define n 131071
char *any_long_str(char *p){
char *pt;
if((pt=(char *)malloc(n))==null){//apply for a larger space for temporary use
printf("apply for temporary use of space to fail...\n");
exit(0);
}
gets(pt);//get a string from the keyboard
if((p=(char *)malloc(strlen(pt)+1))==null){//apply for a suitable size of space
printf("application memory failure...\n");
exit(0);
}
strcpy(p,pt);//copy the string pt to p
free(pt);//release the temporary use of space
return p;
}
int main(void){
char *pstr=null;
printf("input a string:\n");
pstr=any_long_str(pstr);
printf("%s\n",pstr);//look at...
free(pstr);//release the space
return 0;
}