1. ## pointer arithmetic

I have this problem to work through and I wanted some clarification::

Rewrite the following function using pointer arithmmetic instead of array subscripting.

[CODE]

int total_array (int b[], int q)
{
int j, total = 0;
for (j = 0; j < q; j++)
total += b[j];
}

[\CODE]

Would this be rewritten as follows??

[CODE]

int total_array (int b[], in q)
{

int *ptr;
int *total =0;
for (ptr = b; ptr < b + N; ptr++)
total += *ptr;
}

[\CODE]

N is the total elements of array

Not sure if I get pointer arithmetic or it's true purpose
Could someone give me a better explanation than my textbook???

2. This is a quick reply, no guarentee, but there is no reason for total to be a pointer, int q looks like the # of entries, not N.

int total_array (int b[], int q)
{

int *ptr;
int total =0;
for (ptr = b; ptr < b + q; ptr++)
total += *ptr;
}

3. ## ok

Thanks, I think I didn't read my code; total is not supposed to be a pointer.

And I wasn't sure what to do with q (# elements passed to function). My textbook used N in each example and that was throwing me.

Thanks.

4. After the corrections, the code is correct.
What is the point of pointer arithmatic? For the most part, it's just a class exercise to familiarize you with pointers, which are extremely important on their own merit.

Also, code may be more efficient when using pointers rather than arrays. For example, it's not unreasonable that your compiler will compile
b[j]
the same as
*(b + j)
which is clearly less efficient than just
*ptr
the array having to perform an addition every time it does it's thing, while the pointer doesn't need any addition.