Why iterating through an array by incrementing pointer gives such output?
This is my code snippet, I was trying to print the elements of the
arr
by accessing its values from the pointers.
This is the output; look at the first line of the output, why this 33 showed up?
Thanks in advance 😇1 Reply
Basically, iterating an array by a pointer is, most of the time, a risky operation, because with only the pointer, you don't know how long the array is. You are using the value '\0', which is just 0, to stop the iteration, but C does not make any guarantees that any element after the last one in an array has 0. Thus, your loop continues right after the last element, until it finally finds a 0. The iteration could have continued until the program crashed due to a segmentation fault or similar.
I suggest that, in the first loop, you print the addresses that you are using to access, as well as the address of the
i
variable, and the parr
variable. You can do all of them with:
If it looks confusing, the first printf prints the address that parr
is holding, while the third printf prints the address of parr
itself.
My guess as to why it printed 33 and stopped is because the 33 comes from printing whatever i
is holding before being initialized, and the reason it stopped right after is because there might be some padding in the memory place after the i
, and that padding was, by pure coincidence, 0.