Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does the value of a block of memory which stores a integer change repeatedly?
    text
    copied!<p>First of all, I define an integer pointer and class <code>A</code>. I want to pass a pointer to <code>A</code>'s method to store it.</p> <p>I found that the integer member of class <code>A</code> always changes when I invoke a method of <code>A</code>.</p> <p>I'm confused about how to avoid those changes.</p> <pre><code>#include &lt;IOSTREAM&gt; using namespace std; class A { private: int* a; public: A() { }; ~A() { }; void setA(int n) { cout &lt;&lt; "n == " &lt;&lt; n &lt;&lt; "&amp;n == " &lt;&lt; &amp;n &lt;&lt; endl; a = &amp;n; cout &lt;&lt; "now a== " &lt;&lt; a &lt;&lt; endl; } void PassA(int* &amp;outint) { cout &lt;&lt; "a == " &lt;&lt; a &lt;&lt; " *a == " &lt;&lt; *a &lt;&lt;endl; outint = a; cout &lt;&lt; "outint = " &lt;&lt; outint &lt;&lt; endl; } void Print() { cout &lt;&lt; "a ==================== " &lt;&lt; a &lt;&lt; endl; cout &lt;&lt; "*a ==================== " &lt;&lt; *a &lt;&lt; endl; } }; int main() { A A_1; int num = 5; A_1.setA(num); int *intb= NULL ; A_1.PassA(intb); //When the line above done,the value of A_1.a will change. cout &lt;&lt; "intb == " &lt;&lt; intb &lt;&lt; endl; cout &lt;&lt; "*intb ==" &lt;&lt; *intb &lt;&lt; endl; cout &lt;&lt; "num ==" &lt;&lt; num &lt;&lt; endl; A_1.Print(); return 0; } </code></pre> <p><b>Output:</b></p> <pre> n == 5&n == 0x28fe90 now a== 0x28fe90 a == 0x28fe90 *a == 2686708 outint = 0x28fe90 intb == 0x28fe90 *intb ==4619604 num ==5 a ==================== 0x28fe90 *a ==================== 4619604 </pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload