title: C++ pointers: dereferencing, assigning values, etc
body: <p>The questions I'm asking are very basic, but I'm trying to understand the behaviour of pointers in C++ by doing exercises in the compiler. So, for example, I start by declaring an int pointer *p and trying to ascribe it some values and print it:</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  int *p, i;
  int main(){
      i=5;    
      p=&amp;i;
      cout&lt;&lt;*p&lt;&lt;endl;
      return 0;
  }
  </code></pre>
  
  <p>This is very clear and easy, right? But while I'm wondering why the C++ syntax works this way, I test another way of assigning a value to a pointer:</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  int *p, i;
  int main(){
      i=5;    
      p=&amp;i;
      *p=3;
      cout&lt;&lt;*p&lt;&lt;endl;
      return 0;
  }
  </code></pre>
  
  <p>Obviously, the result is different now. The question is, why this wouldn't work:</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  int *p, i;
  int main(){
      *p=3;
      i=5;    
      p=&amp;i;
      cout&lt;&lt;*p&lt;&lt;endl;
      return 0;
  }
  </code></pre>
  
  <p>Why do I have to dereference the pointer first before assigning it a value, but direct assignment would not work without dereferencing? </p>
  
  <p>Also, if in the second example I wrote I added another assignment:</p>
  
  <pre><code>int main(){
      i=5;    
      p=&amp;i;
      *p=3;
      *p=6;
      cout&lt;&lt;*p&lt;&lt;endl;
      return 0;
  }
  </code></pre>
  
  <p>This would not change the value stored at *p (it would still be 3). I don't simply want to learn by memorising this pointer behaviour, I'm interested in understanding why it works this way. Thanks.</p>