Reputation: 25
I have studied how math goes with pointers but there is a thing confusing me
for example :
int ages[]={10,20,30,40,50};
int* ages_ptr=ages;
for(ages_ptr;(ages_ptr-ages)<=4;ages_ptr++)
{
printf("%d"*ages_ptr);
}
(ages_ptr-ages)<=4
here is my question how does result of ages_ptr-ages can be compared to int ?
Upvotes: 0
Views: 56
Reputation: 1413
This line: int *ages_ptr = ages
is roughly equivalent to: int *ages_ptr = &ages[0]
.
This means it it a pointer to the first element of the array. Actually, ages == &ages[0]
.
When you write ages_ptr++
it moves the pointer by sizeof(int)
bytes, so to the next element of the array, so to &ages[1]
, &ages[2]
and so on.
Pointers are just numbers - say, for example, value of &ages[0]
is N
. It has m
elements, so the last element is at the adress of N + (m - 1) * sizeof(int)
.
Initially, value of *ages_ptr
is N
as well. On each iteration i
it moves to N + i * sizeof(int)
.
In the loop condition you have: (ages_ptr - ages) <= 4
. This 4
is actually m - 1
, which makes it (ages_ptr - ages) <= m - 1
. By substitution, we get: N + i - N <= m - 1
, so i < m - 1
, which is i < 4
in our case. (This 4
might be slightly misleading here, as coincidentally pretty often sizeof(int) == 4
as well.)
Notice how sizeof(int)
was dropped in the substitution - because we are dealing with the pointers, the values of addition / subtraction are automatically handled for us. If you write a += x
, you mean shift pointer a
by x elements. If a
is int *
, it actually means a += 1 * sizeof(int)
bytes.
The same goes for subtraction - that's why ages_ptr - ages
returnes number of elements between the two pointers, not number of bytes.
Upvotes: 1