自定义获取线输入功能

chr*_*ris 2 c kernighan-and-ritchie buffer-overflow

我正在阅读K&R的书,我有点卡住了.

以下是什么问题?

void getInput(int* output) {
   int c, i;
   for(i=0; (c = getchar()) != '\n'; i++)
     output[i] = c; // printf("%c", c) prints the c value as expected
   output[++i] = '\0';
}
Run Code Online (Sandbox Code Playgroud)

当我运行程序时,它永远不会离开循环而我必须Ctrl+C退出.但是,如果我用第五行替换printf("%c", c);,它会在输入并创建新行后打印出所有输入.

sun*_*ica 7

以下是什么问题?

1. void getInput(int* output) {
Run Code Online (Sandbox Code Playgroud)

当你想要存储在一个字符数组中时,为什么输入参数是一个int*?大概

void getInput(char* output) {
Run Code Online (Sandbox Code Playgroud)

更好.

另外,你怎么知道输出指针指向你持有足够内存写入用户输入的地方?也许您必须将最大缓冲区长度作为额外参数,以避免PW指出的缓冲区溢出错误.

5.   output[++i] = '\0';
Run Code Online (Sandbox Code Playgroud)

我已经在for循环中增加了一个额外的时间,所以你可以这样做:

output[i] = '\0';
Run Code Online (Sandbox Code Playgroud)

除此之外,程序运行正常并输出我们输入的内容直到返回.

FWIW,我通过调用它来测试它:

 int main(void)
{
    char o[100];
    getInput(o);
    printf("%s", o);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)