【发布时间】:2018-03-24 04:26:14
【问题描述】:
当我想存储我不知道大小的字符串时,该怎么办。
我喜欢这样:
#include <stdio.h>
#include <conio.h>
int main () {
char * str;
str = (char *)malloc(sizeof(char) + 1);
str[1] = '\0';
int i = 0;
int c = '\0';
do {
c = getche();
if(c != '\r'){
str[i] = c;
str[i + 1] = '\0';
i++;
str = (char *)realloc(str, sizeof(char) + i + 2);
}
} while(c != '\r');
printf("\n%s\n", str);
free(str);
return 0;
}
我找到了这个页面: Dynamically prompt for string without knowing string size
正确吗?如果是,那么:
有没有更好的办法?
有没有更有效的方法?
【问题讨论】:
-
conio.h是非标准的。 -
请阅读并理解the question on why not to cast the return value of
malloc()and family in C。另请注意,根据定义,sizeof (char)是一,因为sizeof以char为单位给出其结果。 -
"正确吗?" - 最好自己确定。创建一些测试用例来解决可能出现的问题(例如空输入、很长的输入等)。一旦您确定它的功能符合您的规范,您可能想通过Code Review 寻求批评。请务必先阅读A guide to Code Review for Stack Overflow users,因为那里有些事情的处理方式不同!
-
"有没有更好的办法?" IMO,允许用户消耗无限的内存资源,因为这种方法尝试生成邀请黑客的代码。最好对字符串输入长度有一个合理的有限上限。
-
对于
do...while()循环,将所有内容替换为对readline()的调用。该函数将从堆中为整行分配足够的内存,并返回指向堆中分配区域的指针。 (如果分配失败,则为 NULL)
标签: c string performance pointers memory-management