Reputation: 329
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?
Upvotes: 3
Views: 63
Reputation: 172864
Why does putting *(ptr + 4) inside the for loop cause such a big difference?
Because you're increasing ptr
by ptr++
in the loop, that means (ptr + 4)
will change every time (i.e. moving afterward one by one).
BTW: The condition of the loop are based on the value of the element, not the position. It's correct only when the array being sorted if you want to print out the first nth elements. I suppose it should be:
int *ptr = numArray;
int *end = ptr + 4;
for (ptr; ptr < end; ptr++)
{
std::cout << *ptr << std::endl;
}
Upvotes: 2
Reputation: 16607
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.
Upvotes: 2