Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

c - How could it be possible to read and write past the array

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
", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...