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.
you could use a for cycle instead of a while so instead of
while(i++<size)
you could usefor(i = 0; i < size; i++)
that should solve your problem my friend :)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.
In your loop, the condition
i < size
is checked beforei
is incremented. But,i
is incremented before entering the body of the loop and not after it, so it is possible to accessb[5]
in this case, asi
would be incremented after checkingi < size
withi=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 asegmentation fault
.