简体   繁体   English

为什么这个 C 输入 function 会崩溃?

[英]why does this C input function crash?

#include <stdio.h>

int input(char *s, int n){

    char c;
    int i = 0;

    while((c = getchar()) != '\n' && i < n){
          s[i++] = c; // assigns s[i] then does i++
    }

    s[i]= '\0';

    return i;
}

int main() {

    char array[10];

    input(array, 10);

    printf("%s", array);

}

I have written this code but it does not work.我已经编写了这段代码,但它不起作用。

When i input something it crashes and my shell aborts.当我输入一些东西时它崩溃了,我的 shell 中止了。 Why is this?为什么是这样?

s[i]= '\0';

This will access the array out of bound when you enter more than 9 characters.当您输入超过 9 个字符时,这将越界访问数组。

To prevent this read max n-1 chars.为防止这种情况,最多读取n-1字符。

while((c = getchar()) != '\n' && i < n-1){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么此代码在C中崩溃? (带指针) - Why does this code in C crash? (with pointers) 绑定在C中的数组超出了-为什么这不会崩溃? - Exceeding array bound in C — Why does this NOT crash? 为什么C中的scanf()函数中的多个参数会使应用程序崩溃? - Why multiple arguments in scanf() function in c crash the app? 为什么此C程序无法正常运行? - Why does this C program not function properly? 为什么我的 function 第二次从 python while 循环中调用时崩溃? - Why does my function crash the second time it's called from within a python while loop? 当我将随机数生成器/猜测器放入函数时,我的JavaScript代码崩溃了。 为什么会崩溃? - My javascript code is crashing when I put a random number generator/guesser into a function. Why does it crash? 为什么这个 C 代码(读取文件)在退出(或文件重新分配)时崩溃? - Why does this C code (reading a file) crash upon exit (or file reallocation)? 为什么map函数会更改perl中输入数组的值? - why does map function changes the value of the input array in perl? 为什么我的函数会移动我的输入数据? - Why does my function shift my input data? 为什么我定义的函数不接受数组作为输入? - Why does my defined function not accept an array as an input?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM