I'm trying to brush up my C++ pointer knowledge after years not coding using C++
I have a code like this
#include<iostream>
using namespace std;
void manipulate(int **p) {
cout << "====\n";
cout << "Process 2\n";
cout << **p << '\n';
cout << *p << '\n';
cout << p << '\n';
cout << "====\n";
int a = *(new int(777));
*p = &a;
cout << "====\n";
cout << "Process 3\n";
cout << **p << '\n';
cout << *p << '\n';
cout << p << '\n';
cout << "====\n";
}
int main() {
int *p;
int a = 999;
p = &a;
cout << "====\n";
cout << "Process 1\n";
cout << *p << '\n';
cout << p << '\n';
cout << "====\n";
manipulate(&p);
cout << "====\n";
cout << *p << '\n';
cout << p << '\n';
cout << "Process 4\n";
cout << "====\n";
*p = 888;
cout << "====\n";
cout << "Process 5\n";
cout << *p << '\n';
cout << p << '\n';
cout << "====\n";
manipulate(&p);
return 0;
}
The code prints on my terminal like this
====
Process 1
999
0x7ffee05ea7bc
====
====
Process 2
999
0x7ffee05ea7bc
0x7ffee05ea7c0
====
====
Process 3
777
0x7ffee05ea724
0x7ffee05ea7c0
====
====
1
0x7ffee05ea724
Process 4
====
====
Process 5
1
0x7ffee05ea724
====
====
Process 2
1
0x7ffee05ea724
0x7ffee05ea7c0
====
====
Process 3
777
0x7ffee05ea724
0x7ffee05ea7c0
====
My question is, on the process 4, why it printed 1 on cout << **p << endl;
code? Is it supposed to print 777 instead? Where the value 1 comes from?
Same as process 5, I already assigned the value to *p = 888;
, but the value printed as 1 in the terminal. I thought when you assign value using new int
on process 2, the values will not be destroyed, even after the function calls ends.
Any helps is appreciated, thank you