怎么可能读取和写入数组 [英] How could it be possible to read and write past the array
问题描述
程序输出:
#include <stdio.h>
int main()
{
int size;
printf("Enter the size of array: ");
scanf("%d",&size);
int b[size],i = 0;
printf("Enter %d integers to be printed: ",size);
while(i++ < size)
{
scanf("%d",&b[i]);
printf("%d %d\n", i, b[i]);
}
return 0;
}
对于 size = 5
和输入数字:
0 1 2 3 4
是
1 0
2 1
3 2
4 3
5 4
其中第一列用于 i
,第二列用于数组 b
的元素.
很明显,循环中的i
while(i++
1
.这个循环必须存储/打印 b[1], b[2], b[3], b[4]
处的值,而不是 b[5]
作为循环将在 i = 5
处终止.
这段代码如何打印b[5]
的值?
我已经针对不同的数组 size
对其进行了测试,并且它没有打印任何垃圾值.
where first column is for i
and second for elements of array b
.
It is clear that i
in the loop while(i++ < size) {
incremented to 1
before entering the loop. This loop should have to store/print the value at/of b[1], b[2], b[3], b[4]
but not b[5]
as loop will terminate at i = 5
.
How this code is printing the value of b[5]
?
I have tested it for different array size
and it is not printing any garbage value.
推荐答案
通过读取和写入数组,您的程序会调用未定义的行为.这并不意味着它必须崩溃或打印垃圾值,它可以假装工作正常.显然,这就是本案中发生的事情.
By reading and writing past the array, your program invokes undefined behavior. It doesn't mean that it has to crash or print garbage values, it can pretend working fine. Apparently, that's what is happening in this case.
这篇关于怎么可能读取和写入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!