Thread: pointer arithmetic

  1. #1
    new to C

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


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


    Would this be rewritten as follows??


    int total_array (int b[], in q)

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


    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. #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;
    return total;

  3. #3
    New to C


    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.


  4. #4
    Registered User
    Join Date
    Sep 2001
    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
    the same as
    *(b + j)
    which is clearly less efficient than just
    the array having to perform an addition every time it does it's thing, while the pointer doesn't need any addition.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 04-04-2009, 03:45 AM
  2. Problems passing a file pointer to functions
    By smitchell in forum C Programming
    Replies: 4
    Last Post: 09-30-2008, 02:29 PM
  3. Pointers, arithmetic, and order of operation.
    By Aerie in forum C Programming
    Replies: 4
    Last Post: 04-19-2005, 07:35 AM
  4. Replies: 41
    Last Post: 07-04-2004, 03:23 PM
  5. pointer arithmetic with characters
    By VanJay011379 in forum C++ Programming
    Replies: 6
    Last Post: 07-21-2002, 01:50 PM