C: array sum using pointers [closed]

2019-06-14 17:41发布

问题:

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);

回答1:

You could do something like this.

int array_sum(int *begin, int *end)
{
    int arraysum = 0;
    while (begin < end)
    {
        arraysum += *begin;
        ++begin;
    }
    return arraysum;
}


回答2:

for (p = begin; p < end; p ++)
{
    arraysum += *(arr + p);
}

This doesn't work because you can't add arr and p. You don't need to add anything to p, your number is in *p.

As to why: When you iterate over indicies, i.e. 0 to arraylength - 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 to p and increment P directly, so p starts at the first number, once incremented points at the second number, and so on, until p and end are the same, note the p < end as condition.

dont understand how the loop is incremented. we get at first p = begin (adress number) right ? What does it exactly do at p ++ ? It does p + 1 right ? but adresses of int are of size 4 ???

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).



标签: c arrays sum