在C中获得无限输入?

所以我正在尝试编写一个允许用户输入无限量字符的函数。 例如:

char string[100] 

将输入限制为100个字符。

我到目前为止的代码是:

 #include char* uinput(){ char *string, *current; int counter = 0; string = (char *) malloc(10 * sizeof(char)); do{ realloc(string, counter * sizeof(char)); current = string + counter; *current = getchar(); counter++; }while(*current != '\n'); return string; } int main(){ char *s; s = uinput(); printf("\nYou entered: %s", *s); return 0; } 

我是指针的新手,所以我不确定为什么这不起作用(程序崩溃)。 我要做的是继续读取一个字符并继续重新定位字符串指针,以便字节数不断增加,直到用户按下enter(’\ n’)。

谢谢~Raf

这种方法很明智,但有一些细节是错误的。 如果在启用警告的情况下进行编译,则会注意到您缺少 ; 你也给printf第一个字符而不是指向缓冲区的指针。

然后有一个明显的错误,你的大小被重置为0,并且你正在转换malloc的返回值 ,使用char来存储getchar()的结果,这也是错误的,因为你无法检查EOF 。 你没有保存重新realloc指针; 而且你没有正确地终止字符串。 在次要细节上,您需要将每个realloc的缓冲区大小加倍,因为realloc需要可能复制整行,因此随着行长度的增加,它会随着时间的推移变得越来越慢。

因此我们得到:

 #include  #include  char* uinput() { char *string; // number of characters in the buffer size_t counter = 0; // size of allocated buffer size_t allocated = 16; int c; string = malloc(allocated); // sizeof(char) is 1 do { c = getchar(); if (c == EOF) { break; } // if our buffer is too small, double the allocation if (counter + 2 <= allocated) { size_t new_size = allocated * 2; char *new_buffer = realloc(string, new_size); if (! new_buffer) { // out of memory? try smaller increment new_size = allocated + 16; new_buffer = realloc(string, new_size); if (! new_buffer) { // really out of memory: free old block free(string); return NULL; } } allocated = new_size; string = new_buffer; } // store the character string[counter++] = c; } while (c != '\n'); // terminate the buffer properly string[counter] = 0; return string; } int main() { char *s = uinput(); if (!s) { // possibly out of memory in uinput perror("Error reading input"); exit(EXIT_FAILURE); } printf("\nYou entered: %s", s); free(s); return EXIT_SUCCESS; } 

好吧我认为这是问题所在

你正在重新分配

realloc(string, counter * sizeof(char));

第一次迭代中字符串的大小是多少? 它将是0

现在,您正在写入一个指定了0字节的指针,因此也就是段错误。

将其更改为while loop可以帮助修复它。 您还可以更改计数器的初始值以进行修复

您可以尝试以下内容:

 #include  #include  #include  struct person{ char *name; }pers; void addMem(void); int main(void){ addMem(); printf("\nYour name is:> %s\n",pers.name); free(pers.name); pers.name = NULL; return 0; } void addMem(void){ unsigned int length = 6; size_t newLength = 0; unsigned int newSize = 0; unsigned int i =0; char *name; int c; name = malloc(length); if(name == NULL){ exit(1); } newSize = length; printf("Enter your name:> "); while ((c = getchar()) != '\n' && c!=EOF){ name[i++]=(char)c; if(i == newSize){ newSize = i+length; name = realloc(name, newSize); } } name[i] = '\0'; newLength = strlen(name)+1; pers.name = malloc(newLength); memcpy(pers.name, name, newLength); free(name); name = NULL; } 

另一种方法是使用fgets() ,它从输入流中获取一个大小为缓冲区的字符串; 如果它有完整的输入,则字符串以\n结尾; 如果没有那么它就不会。 因此,您可以循环调用fgets,直到最后有一个EOL字符,然后根据您的程序对输入的作用,您可以决定是继续重新分配还是一次处理一点输入。