How could it be possible to read and write past th

2019-01-20 20:11发布

Output of the program:

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

for size = 5 and input numbers :

0    1    2    3    4

is

1    0
2    1
3    2
4    3
5    4

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.

3条回答
三岁会撩人
2楼-- · 2019-01-20 20:19

you could use a for cycle instead of a while so instead of while(i++<size)you could use for(i = 0; i < size; i++) that should solve your problem my friend :)

查看更多
在下西门庆
3楼-- · 2019-01-20 20:29

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.

查看更多
霸刀☆藐视天下
4楼-- · 2019-01-20 20:42

In your loop, the condition i < size is checked before i is incremented. But, i is incremented before entering the body of the loop and not after it, so it is possible to access b[5] in this case, as i would be incremented after checking i < size with i=4. You do not want that, as this causes undefined program behavior.

If you try to access an element in the array which does not exist, e.g. array[size], you are accessing the next spot in the memory right after the array. In this case you are lucky, but if this meant you were accessing a part of the memory where your program isn't allowed to do so, you'd get a segmentation fault.

查看更多
登录 后发表回答