Pointer to C, I don’t understand how they got this result

here is a piece of code

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 it was calculated 4 4, I don’t understand how they got 3 7(I understand how 3 is calculated, it does not change, since it was not passed by reference)

Thank!

+3
source share
4 answers

In the beginning mainwe have

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

then we call F(m, &n), passing mby value, and a npointer such that

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

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

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

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

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

Next, we change b, so now it bpoints to a:

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

4 , b (- > a)

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

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

m (= 3) n (= ​​7)

+4

F , , :

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
+7

b = &a ;
*b = 4 ;

b ( ). * b, a, n

+1

.:)

F : a, , 7. a ( 7) , b ( n, n 7).

, b, , b a, , b (= > a) 4.

, a, 4, b, a (= > so *b==4, *b==a), m 3 ( , F), n - 7.

, , , , .:)

+1

Source: https://habr.com/ru/post/1768896/


All Articles