下面是返回一个字符指针的函数,该指针指向一个使用getc(stdin)
- 逐个字符初始化的字符串。
内存分配方法有什么缺陷吗?当我们不知道要输入的字符串的大小时,这是一种有效的方法吗?如果不知道,请解释一下。
使用
getc(stdin)
--会不会导致缓冲区溢出???()如果我不能使用
getc(stdin)
,什么可以帮助我以更有效的方式实现我的目标?
到目前为止的代码:
char *getstring()
{
char *str = NULL, *tmp = NULL;
int size = 0, index = 0;
int ch = -1;
int length=0;
while (ch!=0)
{
ch = getc(stdin);
if (ch == '\n')
{
ch = 0;
}
if (size <= index)
{
size += 15;
tmp = (char*)realloc(str, size);
if (!tmp)
{
free(str);
str = NULL;
}
str = tmp;
}
str[index++] = ch;
}
if(size==index)
{
return str;
}
else if(index<size)
{
length=strlen(str);
tmp = (char*)realloc(str,(length+1));
str[index]='\0';
//cout<<"length:"<<length;
str=tmp;
}
return str;
}