Search code examples
cpointersmemoryheap-memorystack-memory

Scope of a pointer in memory


I have been studying C for the past weeks, but I can't fully understand how memory manages pointers.

My question arises from this example obtained from here(page 17 of 19): C-Pointer-Basics

Example code:

 #include <stdio.h>

 void F(int, int *);

 int main()
 {
     int m = 3;
     int n = 5;

     F(m, &n);

     printf("main: %d, %d\n", m, n); // print 3 7 (Where does the 7 came from?)

     return 0;
 }

 void F(int a, int *b)
 {
     /*
      * `a` being a local variable, gets cleaned after `F()` ends
      *  BUT how does `b` retain the value of `&a`?
      */

     a = 7;
     *b = a; // `*b = 7`
     b = &a; // `b` points to `a`
     *b = 4; // `a = 4` and why `*b` doesn't return 4?

     printf("F: %d, %d\n", a, *b); // print 4 4
 }

The question here is:

Why when main() prints the values of m and n, It showsm = 3 and n = 7?

My assumptions:

As I know, a pointer goes beyond the scope of the function where it is declared, so in void F(int a, int *b) when the function is no longer needed, it gets destroyed, same with his parameters, BUT the value of int *b remains in memory right(even though int *b no longer exists)? So if this is true, we can 'recover' it from memory and use it in main().

Best,


Solution

  • For the question why m and n print 3,7 is because the first parameter is passed by value hence it is only getting copied, therefore no modification of the original m is happening and in the case of n, you're passing its address so when you do *b=a the value of a gets copied to n. And then when you do b=&a the pointer b now starts pointing to the address of a instead of that of n. Which is why the second time you do *b=4, you are not modifying n but a.