简体   繁体   English

在循环中使用scanf的程序打印不正确的输出

[英]Program using scanf in a loop prints incorrect output

I don't know what's happening with this code. 我不知道这段代码是怎么回事。

#include<stdio.h>
int main()
   {
   int ii[5], i;
   for (i=1; i<=5; i++)
   {
      scanf("%d", &ii[i]);
   }
   printf("----------------------\n");  
   for(i=1; i<=5; i++)
   printf("%d\n", ii[i]);
   return 0;
   }

After compiling when I provide input as 编译后,当我提供输入为

1 2 3 4 5

then it prints as it is, but when I provide input in reverse order: 然后按原样打印,但是当我以相反的顺序提供输入时:

5 4 3 2 1

it keeps on asking up to some more digits and after that it prints out some random digits from given set of input. 它会继续询问最多一些数字,然后再从给定的输入集中打印出一些随机数字。

How can I fix this? 我怎样才能解决这个问题?

c uses 0 indexing that means that array indexes start at 0 not 1. A for loop over an array should look like this: c使用0 indexing ,这意味着数组索引从0开始而不是1。数组的for循环应如下所示:

int array[ARRAY_LENGTH], i;
for (i = 0; i < ARRAY_LENGTH; ++i) {

This will ensure that i will go from 0 to ARRAY_LENGTH - 1 and will not go outside the bounds of your array. 这将确保i0ARRAY_LENGTH - 1并且不会超出数组的范围。

These lines: 这些行:

for(i=1; i<=5; i++)
printf("%d\n", ii[i]);

will Access element 5 of ii where the maximum index is 4. This will cause Undefined Behavior which is likely why you are seeing random numbers appear. 将访问ii元素5 ,其中最大索引为4。这将导致未定义行为 ,这很可能是您看到随机数的原因。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM