tags:

views:

1299

answers:

7

Trying to understand the behaviour of pointers in C, i was a little surprised by the following (example code below):

#include <stdio.h>

void add_one_v1(int *our_var_ptr)
{
    *our_var_ptr = *our_var_ptr +1;
}

void add_one_v2(int *our_var_ptr)
{
    *our_var_ptr++;
}

int main()
{
    int testvar;

    testvar = 63;
    add_one_v1(&(testvar));         /* try first version of the function */
    printf("%d\n", testvar);        /* prints out 64                     */
    printf("@ %p\n\n", &(testvar));

    testvar = 63;
    add_one_v2(&(testvar));         /* try first version of the function */
    printf("%d\n", testvar);        /* prints 63 ?                       */
    printf("@ %p\n", &(testvar));   /* address remains identical         */
}

/*

OUTPUT:

64
@ 0xbf84c6b0

63
@ 0xbf84c6b0

*/

My question is: what exactly does the *our_var_ptr++ statement in the second function (add_one_v2) do since it's clearly not the same as *our_var_ptr = *our_var_ptr +1?

+2  A: 

The '++' operator has higher precedence over the '*' operator, which means that the pointer address will be incremented before being dereferenced.

The '+' operator, however, has lower precedence than '*'.

Martin Cote
Ah! No. The ++ binds more tightly, so it is the pointer that is incremented. But it is the post-increment version, so it happens *after* the dereference. So: dereference the pointer and return a value, then increment the pointer (not the value pointed to).
dmckee
+10  A: 

Due to operator precedence rules and the fact that ++ is a postfix operator, add_one_v2() does dereference the pointer, but the ++ is actually being applied to the pointer itself. However, remember that C always uses pass-by-value: add_one_v2() is incrementing its local copy of the pointer, which will have no effect whatsoever on the value stored at that address.

As a test, replace add_one_v2() with these bits of code and see how the output is affected:

void add_one_v2(int *our_var_ptr)
{
    (*our_var_ptr)++;  // Now stores 64
}

void add_one_v2(int *our_var_ptr)
{
    *(our_var_ptr++);  // Increments the pointer, but this is a local
                       // copy of the pointer, so it doesn't do anything.
}
htw
That isn't true about the order of operation. In add_one_v2, the ++ is applied to the pointer, not the dereference. However, since it is a post increment, the dereference is happening BEFORE the increment.
Torlack
Are you talking about the original add_one_v2, or one of my examples with parentheses?
htw
I'm talking about the original. I'm just trying to point out that your statement of "is incrementing the pointer and then dereferencing..." is incorrect.
Torlack
Thanks for the quick answer (and for the informative comment Torlack!). ++*our_var_ptr seems to 'work' the same as add_one_v1.One thing i don't understand though: if the functions are only working with local copies of the pointers --> how do they achieve to influence the value printed in main? Or do i misinterpret that statement?
ChristopheD
The pointer itself is a local copy, but the value it is pointing at isn't.
Torlack
@Torlack: Gotcha, thanks for the reminder. Fixed. @ChristopheD: If you dereference a pointer, you can change the value stored in that location in memory. So, basically, you have a copy of the *memory address* of the value—you can't influence what memory address the pointer will hold in main, but you can change what value that memory address points to.
htw
Thanks a lot (htw, torlack): that makes sense!
ChristopheD
+10  A: 

This is one of those little gotcha's that make C and C++ so much fun. If you want to bend your brain, figure out this one:

while (*dst++ = *src++) ;

It's a string copy. The pointers keep getting incremented until a character with a value of zero is copied. Once you know why this trick works, you'll never forget how ++ works on pointers again.

P.S. You can always override the operator order with parentheses. The following will increment the value pointed at, rather than the pointer itself:

(*our_var_ptr)++;
Mark Ransom
Thanks for this really nice example!
ChristopheD
+3  A: 

As the others have pointed out, operator precedence cause the expression in the v2 function to be seen as *(our_var_ptr++).

However, since this is a post-increment operator, it's not quite true to say that it increments the pointer and then dereferences it. If this were true I don't think you'd be getting 63 as your output, since it would be returning the value in the next memory location. Actually, I believe the logical sequence of operations is:

  1. Save off the current value of the pointer
  2. Increment the pointer
  3. Dereference the pointer value saved in step 1

As htw explained, you aren't seeing the change to the value of the pointer because it is being passed by value to the function.

Dave Costa
Thanks for this nice explanation!
ChristopheD
+2  A: 

our_var_ptr is a pointer to some memory. ie it is the memory cell where the data is stored. (n this case 4 bytes in the binary format of an int).

*our_var_ptr is the dereferenced pointer - it goes to the location the pointer 'points' at.

++ increments a value.

so. *our_var_ptr = *our_var_ptr+1 dereferences the pointer and adds one to the value at that location.

Now add in operator precedence - read it as (*our_var_ptr) = (*our_var_ptr)+1 and you see that the dereference happens first, so you take the value and incremement it.

In your other example, the ++ operator has lower precedence than the *, so it takes the pointer you passed in, added one to it (so it points at garbage now), and then returns. (remember values are always passed by value in C, so when the function returns the original testvar pointer remains the same, you only changed the pointer inside the function).

My advice, when using dereferencing (or anything else) use brackets to make your decision explicit. Don't try to remember the precedence rules as you'll only end up using another language one day that has them slightly different and you'll get confused. Or old and end up forgetting which has higher precedence (like I do with * and ->).

gbjbaanb
Thanks for answering, i think the advice about making it more explicit by using brackets is solid!
ChristopheD
+2  A: 

OK,

*our_var_ptr++;

it works like this:

  1. The dereference happens first, giving you the memory location indicated by our_var_ptr (which contains 63).
  2. Then the expression is evaluated, the result of 63 is still 63.
  3. The result is thrown away (you aren't doing anything with it).
  4. our_var_ptr is then incremented AFTER the evaluation.

It is effectively the same as doing this:

*our_var_ptr;
our_var_ptr = our_var_ptr + 1;

Make sense? Mark Ransom's answer has a good example of this, except he actually uses the result.

CodeSlave
Thanks, very clear explanation!
ChristopheD
+2  A: 

Much confusion here, so here is a modified test program to make what happens clear (or at least clear*er*):

#include <stdio.h>

void add_one_v1(int *p){
  printf("v1: pre:   p = %p\n",p);
  printf("v1: pre:  *p = %d\n",*p);
    *p = *p + 1;
  printf("v1: post:  p = %p\n",p);
  printf("v1: post: *p = %d\n",*p);
}

void add_one_v2(int *p)
{
  printf("v2: pre:   p = %p\n",p);
  printf("v2: pre:  *p = %d\n",*p);
    int q = *p++;
  printf("v2: post:   p = %p\n",p);
  printf("v2: post:  *p = %d\n",*p);
  printf("v2: post:   q = %d\n",q);
}

int main()
{
  int ary[2] = {63, -63};
  int *ptr = ary;

    add_one_v1(ptr);         
    printf("@ %p\n", ptr);
    printf("%d\n", *(ptr));  
    printf("%d\n\n", *(ptr+1)); 

    add_one_v2(ptr);
    printf("@ %p\n", ptr);
    printf("%d\n", *ptr);
    printf("%d\n", *(ptr+1)); 
}

with the resulting output:

v1: pre:   p = 0xbfffecb4
v1: pre:  *p = 63
v1: post:  p = 0xbfffecb4
v1: post: *p = 64
@ 0xbfffecb4
64
-63

v2: pre:   p = 0xbfffecb4
v2: pre:  *p = 64
v2: post:  p = 0xbfffecb8
v2: post: *p = -63
v2: post:  q = 64

@ 0xbfffecb4
64
-63

Four things to note:

  1. changes to the local copy of the pointer are not reflected in the calling pointer.
  2. changes to the target of the local pointer do affect the target of the calling pointer (at least until the target pointer is updated)
  3. the value pointed to in add_one_v2 is not incremented and neither is the following value, but the pointer is
  4. the increment of the pointer in add_one_v2 happens after the dereference

Why?

  • Because ++ binds more tightly than * (as dereference or multiplication) so the increment in add_one_v2 applies to the pointer, and not what it points at.
  • post increments happen after the evaluation of the term, so the dereference gets the first value in the array (element 0).
dmckee
Thanks for taking the time for writing this answer, it's this kind of stuff that makes StackOverflow so great an environment! I've had more insightful answers here in one hour than i would have found in the same time in my lousy C tutorials ;)
ChristopheD