它怎么可能读写过去数组 [英] How could it be possible to read and write past the array

查看:125
本文介绍了它怎么可能读写过去数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序的输出:

#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;       
}

尺寸= 5 键,输入数字:

0    1    2    3    4

1    0
2    1
3    2
4    3
5    4

,其中第一列是 I 和第二数组 B 的元素。结果
很显然, I 在循环同时(我++ LT;大小){递增到 1 进入循环之前。这个循环应该有存储/打印在 B [1],B [2],B [3],B [4] 而不是<$的C /价值$ C> b [5] 作为循环将终止 I = 5 。结果
如何这code是印刷的值B [5] 结果
我测试了不同的数组尺寸并没有打印任何垃圾值。

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.

推荐答案

通过读取和写入过去的数组,你的程序调用未定义的行为。这并不意味着它的不得不崩溃或打印垃圾值,它可以pretend工作的罚款。显然,这就是在这种情况下发生的。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆