title: Segmentation fault from accessing 2d array passed to a function
body: <p>I am using Code:Block.</p>
  
  <p>Compiled the following code(no errors) and while running got segmentation fault.</p>
  
  <pre><code>void print(int size, int **a)
  {
      for(int i=0;i&lt;size;i++)
      {
          for(int j=0;j&lt;size;j++)
          {
              cout&lt;&lt;a[i][j]&lt;&lt;" ";/**Segmentation fault here**/
          }
          cout&lt;&lt;endl;
      }
  }
  
  int main()
  {
      int a[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
      int size = sizeof(a)/sizeof(a[0]);
      print(size,(int **)a);
      return 0;
  } 
  </code></pre>
  
  <p>I tried using different methods of passing the array:</p>
  
  <pre><code>void print(int size, int a[][4])
  {
      for(int i=0;i&lt;size;i++)
      {
          for(int j=0;j&lt;size;j++)
          {
              cout&lt;&lt;a[i][j]&lt;&lt;" ";
          }
          cout&lt;&lt;endl;
      }
  }
  
  int main()
  {
      int a[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
      int size = sizeof(a)/sizeof(a[0]);
      print(size,a);
      return 0;
  } 
  </code></pre>
  
  <p>I got no error, code ran successfully.</p>
  
  <p>For the first code instead of using <code>a[i][j]</code>, I tried with <code>*(*(a+i)+j)</code>, got segmentation fault. </p>
  
  <p>Then I debugged the first code at the point of segmentation fault and absorbed the following:</p>
  
  <pre><code>&gt; p a
  $1 = (int **) 0x22fd30
  &gt; p *a
  $2 = (int *) 0x200000001
  &gt; p **a
  Cannot access memory at address 0x200000001
  </code></pre>
  
  <p>I believe that <code>a</code> hold the first address of the 2d array. but for p **a there is a different address shown in the error message.</p>
  
  <p>Then I ran the first code in <a href="http://ideone.com/" rel="nofollow">http://ideone.com/</a> and encountered run time error. Where am I making mistake? and why the debugger showing different address?.</p>