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;
}
The result isn’t undefined. You pass the pointer
jby value, so you modify a copy of it inside the function. The originaljis left unchaged, so the result is still10.