這裏的邏輯是錯誤的:
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));
(它不應該有cast,BTW,因爲這是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;
}
這是偉大的,先生。但我仍然得到一個TLE。 ((c = getchar())!='\ n'){_ _ realloc(input,(sizeof(char))); _ _ input [i ++] = c; _ ( )之後替換此段代碼 _while _} _ 與你的。 –
您是否應用了以上所有三個錯誤修復程序? –
沒有,我基本上只應用while循環中的一個。 我應該全部應用嗎? –