Thread: Question about pointer arithmetic:

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    7

    Question about pointer arithmetic:

    Hi, I just want to make sure of something. Say we have the following declarations:
    Code:
    int list[6] = {10, 20, 30, 40, 50, 60};
    int *p = list;
    Given this information, we were given an exercise to do in class about pointer arithmetic.
    I understand that *++p = 20, by first incrementing p and dereferencing, and the following code of *p++ = 20 also because p is pointing to the second element of the array, dereferences, and then increments p to the next element. The code after that, however, is *(p++) which evaluates to 30, which I'm a little confused about. Shouldn't it be 40? Since the code previous to that incremented p already to point to list[2], and it's incrementing p first to point to list[3] then dereferencing? Only way I could see it being 30 is if *(p++) is the same as *p++, but it seems like that defies the rule of precedence.

  2. #2
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    You would think so but the rules for expressions involving postfix ++ operators are a bit nebulous. Here's an excerpt from the C ref manual:
    Code:
    
    7.2.8  lvalue-expression++
           The result is the value of the object referred to by the lvalue expression. After the result is noted,
           the object referred to by the lvalue is incremented in the same manner as for the prefix ++ operator...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 04-04-2009, 03:45 AM
  2. Pointer Arithmetic and Typecasting
    By pobri19 in forum C Programming
    Replies: 2
    Last Post: 03-19-2009, 11:06 PM
  3. a pointer to a function question..
    By transgalactic2 in forum C Programming
    Replies: 17
    Last Post: 10-21-2008, 11:47 AM
  4. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  5. Pointer arithmetic question
    By moneil in forum C Programming
    Replies: 6
    Last Post: 03-25-2004, 11:45 PM