[英]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.