Reputation: 458
I expect the result is undefined or something, but the output is "10", why?
I suppose the memory is destroyed after the function gets called.
#include <iostream>
void f(int *p)
{
int l = 20;
int *k = &l;
p = k;
}
int main()
{
int i = 10;
int *j = &i;
f(j);
std::cout << *j;
return 0;
}
Upvotes: 0
Views: 136
Reputation: 171167
There is absolutely nothing wrong with the code. The parameter of f
is not passed by reference, so f
has no way to modify j
, therefore j
still points to i
after f
exits.
Upvotes: 1
Reputation: 17110
You are confused about passing by reference / passing by value. While you are passing a pointer, the pointer itself is a number that you pass to the f()
function pointing to a chunk of memory; modifying the *p variable in f()
(rather than the chunk of memory where *p
points to) will have no effect in the main()
function.
A pointer is just a variable that holds an address of memory. In itself, it is passed by value; only the variable to which the pointer points is passed by reference.
Upvotes: 0
Reputation: 13661
Lets decompose your code.
You first assign 10 to i
. Then make j
point to the adress of i
.
In f, you set the value of p
, and not the value it points to, to k
. As passed as a parameter of f()
, p value is copied (the adress value).
In consequence, you never modify the value pointed by j
, simply the local value of j
in f()
, that is why it stays equal to 10
.
Upvotes: 1
Reputation: 122001
The program is well formed as the local variable l
is not accessed outside of f()
as the pointer j
is unchanged in main()
(a copy of the pointer j
is passed to f()
).
Upvotes: 1
Reputation: 258618
The result isn't undefined. You pass the pointer j
by value, so you modify a copy of it inside the function. The original j
is left unchaged, so the result is still 10
.
Upvotes: 5