#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i = 0;
char c, *input;
input = (char *) malloc(sizeof(char));
if(input == NULL) {
printf("NOT ENOUGH SPACE!");
exit(1);
}
printf("Input a string, press ENTER when done: ");
while((c = getchar()) != '\n') {
realloc(input, (sizeof(char)));
input[i++] = c;
}
input[i] = '\0';
printf("\nYou've entered the string: %s\n", input);
}
上面的代码片段适用于小输入。但是只要提供的输入很大,它就会失败。存在运行时错误或段错误。 内存空间的重新分配可能有一些错误。 我基本上想从用户动态存储一个字符数组,即不提及用户可以直接放入任何大小的字符数组的输入容量。
最佳答案
这里的逻辑是错误的:
while((c = getchar()) != '\n') {
realloc(input, (sizeof(char)));
input[i++] = c;
}
您实际上并没有增加缓冲区的大小,而且您还丢弃了 realloc
的结果。
尝试:
while ((c = getchar()) != '\n') {
// Note: you need one extra character for the terminator, so for the
// first char, when `i` is 0, then you need room for two `char`s in
// the buffer - one for the first input character and one for the
// terminator. And so on...
char * temp = realloc(input, i + 2); // NB: realloc can, and sometimes does, fail
if (temp == NULL) // if realloc failed then exit program
exit(1);
input = temp; // otherwise update input...
input[i++] = c;
}
此外,由于您总是要对每个字符调用 realloc(顺便说一下,这是非常低效的,但它有效),这一行:
input = (char *) malloc(sizeof(char));
(不应该有类型转换,顺便说一句,因为这是 C,而不是 C++)可以是:
input = NULL;
最后一个错误:
char c;
应该是:
int c;
否则您的 while
循环可能永远不会终止,因为 EOF
只能正确表示为 int
。
所以最终的固定程序应该是这样的:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i = 0;
int c;
char * input = NULL;
printf("Input a string, press ENTER when done: ");
while ((c = getchar()) != '\n') {
// Note: you need one extra character for the terminator, so for the
// first char, when `i` is 0, then you need room for two `char`s in
// the buffer - one for the first input character and one for the
// terminator. And so on...
char * temp = realloc(input, i + 2); // NB: realloc can, and sometimes does, fail
if (temp == NULL) // if realloc failed then exit program
exit(1);
input = temp; // otherwise update input...
input[i++] = c;
}
input[i] = '\0';
printf("\nYou've entered the string: %s\n", input);
return 0;
}
关于c - 动态大小字符数组中的运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43355969/