我一直在尝试用 C(使用 dev-c++)制作一个简单的控制台应用程序,它读取字符并将它们放入数组中,同时动态地延长数组以容纳任意数量的字符,直到您按下回车键。代码是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
main()
{
int x=0;
char * ch1;
ch1 = (char*) malloc(1);
do
{
ch1[x] = getche();
x++;
ch1 = (char*) realloc (ch1,x);
} while (ch1[x-1]!='\n');
printf("Input Sentence Is :%s",ch1);
free(ch1);
}
虽然程序运行良好且没有错误,但在您键入句子并按回车键而不是简单地打印句子后,“光标”会移回窗口的开头,您可以继续在前面的字符上方键入。
编辑:我知道这不是最佳方法,因为您失去了退格键功能,例如我只是想看看在我们今天学习 malloc 和 realloc 之后它是否可行。
最佳答案
我几乎可以肯定这就是您尝试要做的。它与您的代码之间的区别应该很明显:
- 使用
calloc()
作为初始缓冲区以确保它被终止, - 检查输入流 EOF 以及 CR 和 LF 字符。
x
代表缓冲区长度,不是字符串长度。- 在每次成功扩展时建立字符串终止。
- 计算内存分配失败。
main()
的符合标准的声明,- 使用符合标准的
getchar()
进行输入。
代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *ch1 = calloc(1,1), *tmp;
size_t x = 1;
int c;
if (!ch1)
{
perror("Failed to allocate string buffer.");
exit(EXIT_FAILURE);
}
while ((c = getchar()) != EOF && c != '\r' && c != '\n')
{
tmp = realloc(ch1, x+1);
if (!tmp)
{
// note: the string at ch1 still valid.
perror("Failed to resize string buffer.");
break;
}
ch1 = tmp;
ch1[x - 1] = c;
ch1[x++] = 0;
}
printf("Input Sentence: %s\n", ch1);
free(ch1);
return 0;
}
希望对您有所帮助。
关于c - C 中带有 malloc 和 realloc 的动态字符串数组不会退出循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23835186/