2017-04-11 27 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循环中的一个。 我应该全部应用吗? –