简体   繁体   中英

Checking pointer address and value from a function

I'm a beginner to C and have been reading a book called "Understanding and Using C Pointers" and ended up running into a problem with using the printf function.

When using debug_p, it turns out that the address of the pointer num_p is different but exact to num in debug, but it returns the correct value when attempting a printf within main().

My question is, why is this so? Is there an appropriate way to do a printf within a function and have a correct address of a pointer?

#include <stdio.h>
void debug(int num)
{
    printf("Address of num: %i Value: %i\n", &num, num);
}

void debug_p(int *num_p)
{
    printf("Address of num_p: %i Value %i\n", &num_p, num_p);

}


int main()
{
int num=11;
int *num_p=&num;
printf("Address of num: %i Value: %i\n", &num, num);
printf("Address of num_p: %i Value: %i\n\n", &num_p, num_p);

debug(num);
debug_p(num_p);
return 0;
}

Output from main():

Address of num: 2358860 Value: 11
Address of num_p: 2358848 Value: 2358860

Output from debug, then debug_p:

Address of num: 2358816 Value: 11
Address of num_p: 2358816 Value 2358860

When you pass a variable to a function, you only pass the value of this variable. You never pass the address, because a new variable is created in that function. The parameters that you see in the signature of the function are all local variables, just like you would write them in the function body. These parameters are filled with the value that you pass when you call the function - but again, you are just passing the value to new variables.

void function(int a) { printf(a); }

int a = 5;
function(a);

In this example, there exist two distinct variables which have completely different addresses. They just have the same value (which is 5), but their addresses are very different.

The same happens in your debug function: num in there is not the same variable as num in main , they just have the same value (because you "gave" the value of num in main to num in debug ), but not the same address. Now since num_p in debug_p still points to num in main and not to num in debug , the addresses are different.

The reason why num and num_p have the same address in both functions is because of how the stack works: The first call to debug allocates a variable on the stack. Then, when the function returns, the stack is freed again. Now you call debug_p , and therefore another variable is allocated. It will use the same place in memory as before, because the stack is built up in the same way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM