C语言scanf输入数组元素异常:仅接收第二个元素即终止
C语言数组输入程序提前终止问题解决
问题重现
我写了一个逐个输入数组元素的C程序,但程序接收第二个元素就终止了,尝试在scanf里加\n后情况有变化,但问题依然存在。
原代码
#include <stdio.h> int main() { int n; int arr[n]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } for (int x = 0; x < n; x++) { printf("%d", arr[x]); } return 0; }
原运行结果
5 1 2 12 -------------------------------- Process exited after 1.99 seconds with return value 0 Press any key to continue . . .
修改后的尝试(在第二个scanf加\n)
修改后的scanf语句:scanf("%d\n", &arr[i]);
运行结果:
5 1 2 3 12 -------------------------------- Process exited after 5.1 seconds with return value 0 Press any key to continue . . .
问题原因
核心错误:未初始化变量就定义变长数组
代码里先定义了变长数组arr[n],但此时n还没被赋值,它的值是内存中的随机垃圾值。这会导致数组实际大小完全不可控,后续输入元素时极易触发内存越界,引发程序未定义行为,表现为提前终止。加
\n的误区
在scanf格式串里加\n,会让scanf跳过所有空白字符(换行、空格、制表符等),直到读取到非空白字符才结束当前输入操作。这就是修改后需要输入更多值才会终止的原因,但根本的数组大小未正确初始化问题并没有解决。
正确代码
把获取数组大小的scanf移到定义数组之前,确保n有确定值后再创建数组:
#include <stdio.h> int main() { int n; // 先获取数组大小 scanf("%d", &n); // 用已初始化的n定义变长数组 int arr[n]; for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } for (int x = 0; x < n; x++) { printf("%d", arr[x]); } return 0; }
正确运行示例
输入:
5 1 2 3 4 5
输出:
12345
内容的提问来源于stack exchange,提问作者Vien Nguyen
相关产品推荐
相关产品推荐

