Does a function parameter in C have the same memory address?

Ok, so C is a pass by value, which means that instead of the original variable for the parameter, a copy of the variable is used, right? So, will this copy always have the same memory address? Consider this code:

void test(int *ptr) { printf("&ptr: %p\n", &ptr); printf("ptr: %p\n", ptr); printf("*ptr: %d\n\n", *ptr); } int main() { int a = 1, b = 2, c = 3, d = 4, e = 5; test(&a); test(&b); test(&c); test(&d); test(&e); return 0; } 

The result obtained from this code is as follows:

 &ptr: 0x7fff70536728 ptr: 0x7fff7053674c *ptr: 1 &ptr: 0x7fff70536728 ptr: 0x7fff70536750 *ptr: 2 &ptr: 0x7fff70536728 ptr: 0x7fff70536754 *ptr: 3 &ptr: 0x7fff70536728 ptr: 0x7fff70536758 *ptr: 4 &ptr: 0x7fff70536728 ptr: 0x7fff7053675c *ptr: 5 

I had a no feeling. I understand that ptr does not exist outside the test() code. So why is &ptr same for all five function calls?

+6
source share
1 answer

&ptr is the same as ptr is a local variable inside test() . Since you call test() five times in a row without any intervention, it just gets the same address on the stack every time it is called (note: this is not required by C - this is just how your machine does it and as it usually happens).

If you call the second function, which itself is called test() , you won’t get the same result for &ptr , since this is the space on the stack that ptr used to be in, is now using an intermediate function call.

For instance:

 #include <stdio.h> void test(int *ptr) { printf("&ptr: %p\n", (void *) &ptr); printf("ptr: %p\n", (void *) ptr); printf("*ptr: %d\n\n", *ptr); } void test_test(void) { int a = 1; test(&a); } int main() { int a = 1, b = 2, c = 3, d = 4, e = 5; test(&a); test(&b); test(&c); test(&d); test(&e); test_test(); return 0; } 

gives:

 paul@local :~/src/c/scratch$ ./ptrtest &ptr: 0x7fff39f79068 ptr: 0x7fff39f7909c *ptr: 1 &ptr: 0x7fff39f79068 ptr: 0x7fff39f79098 *ptr: 2 &ptr: 0x7fff39f79068 ptr: 0x7fff39f79094 *ptr: 3 &ptr: 0x7fff39f79068 ptr: 0x7fff39f79090 *ptr: 4 &ptr: 0x7fff39f79068 ptr: 0x7fff39f7908c *ptr: 5 &ptr: 0x7fff39f79048 ptr: 0x7fff39f7906c *ptr: 1 paul@local :~/src/c/scratch$ 

and you can see that &ptr is different from the last call made via test_test() .

+6
source

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


All Articles