tags:

views:

113

answers:

4

here is code snippet

void F (int a, int *b)
{
 a = 7 ;
 *b = a ;
 b = &a ;
 *b = 4 ;
 printf("%d, %d\n", a, *b) ;
}
int main()
{
 int m = 3, n = 5;
 F(m, &n) ;
 printf("%d, %d\n", m, n) ;
 return 0;
}

answer

4 4 
3 7

I see how 4 4 was computed, I don't get how they got 3 7 (I do understand how 3 is computed, it is not changed since it was not passed by reference)

Thanks !

+7  A: 

I've annotated the F function with comments to explain what's going on:

a = 7 ;  // a is now 7
*b = a ; // b points to n, so n is now 7
b = &a ; // b now points to a and no longer to n
*b = 4 ; // a is now 4. n is unaffected
sepp2k
+1  A: 

Take a close look at this line

b = &a ;
*b = 4 ;

b gets the reference of a (it's memory address). When you now access *b it points to the memory of the variable a, not to n anymore

Tseng
+1  A: 

Quite subtle indeed. :)

In F a lot of nonsense happens: whichever value is passed via a, it's discarded, and instead 7 is assigned to it. Then, the value of a (which is 7) is assigned to the variable to which b points (which is n, so it's here that n becomes 7).

At the next line, the object to which b points is changed, so that b now points to the local parameter a, and at the following line the object pointed by b (=>a) is set to 4.

Thus, now we have a that is 4, b that points to a (=>so *b==4, since *b==a), m is still 3 (it was passed by value, so it couldn't have been changed by F) and n was set to 7.

By the way, this is exactly the mess you shouldn't to at all in your applications to avoid confusing any people who have the disgrace to work on them. :)

Matteo Italia
Of course the whole function is non-sense. But it's the typical code examples you use in learning books and tutorials to demostrate how (in this case) pointers and references work
Tseng
I know, I was just pointing out that it's not the way pointers are usually used, otherwise any C program would be an incomprehensible mess (although some people would argue that this is true :S ).
Matteo Italia
+4  A: 

At the start of main, we have

m=3   n=5  // int m = 3, n = 5;

then we call F(m, &n), passing m by value, and n by pointer such that

m = 3   n = 5
a = 3   b->n   // F(m, &n);

Now, inside F(), we assign 7 to a:

m = 3   n = 5
a = 7   b->n     // a = 7

then we assign a (=7) to the memory address pointed by b (->n)

m = 3   n = 7
a = 7   b->n     // *b = a;

next we change b, so that now b points to a:

m = 3   n = 7
a = 7   b->a     // b = &a;

and then we assign 4 to the memory address pointed by b (->a)

m = 3   n = 7
a = 4   b->a     // *b = 4;

printing a (=4) and *b (->a =4)

and printing m (=3) and n (=7) outside the function

Lie Ryan