How could I get the sum of an array using only pointers ?
int array_sum(int *begin, int *end)
{
int arraysum = 0;
int *p = 0;
for (p = begin; p < end; p ++)
{
arraysum += *(arr + p);
}
return arraysum;
}
this doesn't compile at line
arraysum += *(arr + p);
This doesn't work because you can't add
arr
andp
. You don't need to add anything top
, your number is in*p
.As to why: When you iterate over indicies, i.e.
0
toarraylength - 1
, you always use the begin pointer and add the index to it to find you number. In your loop however, you copy the beginning pointer top
and incrementP
directly, sop
starts at the first number, once incremented points at the second number, and so on, untilp
andend
are the same, note thep < end
as condition.Pointer-Arithmetic makes this possible. Math on pointers works a bit different, essentially making sure that you add/subtract multiples of the objects size. So adding one to your int-pointer actually adds
sizeof(int)
under the hood. This is also how array-indicies work,array[i]
is equivalent to*(array + i)
.You could do something like this.