I am a newbie trying to wrap his head around the concept of pointers. It has been going well so far except for when I am trying to play around with arrays using a for loop. Instead of indexing the array in a normal manner, I am using a pointer instead. This is where I have noticed some peculiarities that I cannot understand.
So, for example. say I wanted to print the first four values of numArray:
int numArray = [1, 5, 10, 15, 20]
Now with a pointer, my approach was this:
int *ptr = numArray;
for (ptr; *ptr < *(ptr + 4); ptr++)
{
std::cout << *ptr << std::endl;
}
Which doesn't work, despite my thinking that *(ptr + 4) would be the same as numArray[4].
However, if I deal with the stopping condition slightly differently:
int *ptr = numArray;
int end = *(ptr + 4);
for (ptr; *ptr < end; ptr++)
{
std::cout << *ptr << std::endl;
}
Then it suddenly gives me what I want, despite the code not being drastically different.
So why does this happen? I feel like the answer might be very obvious but I'm not grasping it. Why does putting *(ptr + 4) inside the for loop cause such a big difference? Why exactly do pointers behave this way?
for (ptr; *ptr < *(ptr + 4); ptr++)
/* after ptr is incremented (ptr+4) is again calculated in iterations */
In this loop after first iteration *(ptr+4) will go out of bounds(as it is calculated in every iteration) as you increment ptr and dereferencing it causes undefined behaviour. And same thing happens in next iterations .
Above doesn't happen in latter case as end remains constant and does not change with ptr as ptr is incremented and , therefore it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With