0
Address of a variable
Please help me to understand the output...(I understand that the variables in the same scope have same address) but here I'm not getting how this addresses are actually working out. #include <stdio.h> void f(int p) { printf("The address of p inside f() is %p\n", &p); } void g(int r) { printf("The address of r inside g() is %p\n", &r); f(r); } int main() { int a = 55; printf("The address of a inside main() is %p\n", &a); f(a); g(a); return 0; } /* The address of a inside main() is 0x7ffe12bb471c The address of p inside f() is 0x7ffe12bb46fc The address of r inside g() is 0x7ffe12bb46fc The address of p inside f() is 0x7ffe12bb46dc */ https://code.sololearn.com/ca120a18a141
3 Answers
+ 1
When formal parameters are passed into a function declaration, c++ implicitly creates a new variable of their type and assign a new address to them. This means You're actually creating a new copy of the argument with different memory's location.
If you must get a constant address, then all your function declaration must explicitly call it arguments by their reference. For example, the f function could be
void f(const int &a) ;
Instead of
void f(int a) ;
0
@Mirielle Thank you for this! But I'm in confusion...I need little more clarification.
My point is that :
If I'm creating a copy of the argument with different memory location then why f() local variable p and g() local variable r have same address? Aren't after the execution of f(), memory occupied by it's variable will get deallocated as the end of the scope of variable is reached? and when g() will execute it's variable should be get allocated to different memory location?
0
Functions call appears in stack. from the current stack, the parameter of g is created and everyother part of g uses it's value since there's no redeclaration.