2017-04-11 30 views
0
#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); 
} 

上面的代碼片段適用於小輸入。但只要提供的輸入尺寸很大,就會失敗。無論是運行時錯誤還是分段錯誤。 在重新分配內存空間時可能會出現一些錯誤。 我基本上想要從用戶動態存儲一個字符數組,即沒有提及用戶可以直接放入任何字符數組大小的輸入容量。動態大小字符數組中的運行時錯誤

回答

2

這裏的邏輯是錯誤的:

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; 
} 
+0

這是偉大的,先生。但我仍然得到一個TLE。 ((c = getchar())!='\ n'){_ _ realloc(input,(sizeof(char))); _ _ input [i ++] = c; _ ( )之後替換此段代碼 _while _} _ 與你的。 –

+0

您是否應用了以上所有三個錯誤修復程序? –

+0

沒有,我基本上只應用while循環中的一個。 我應該全部應用嗎? –