Output of the program:
#include
int main()
{
int size;
printf(\"Enter the size of array: \");
scanf(\"%d\",&size);
i
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 :)
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 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
.