title: C++: Crashes when 2D array element is referenced while overloading ostream >>
body: <p>I'm attempting to create a Matrix class that contains a 2D array using dynamically allocated memory. </p>
  
  <pre><code>class Matrix{
    int sized;
    Complex **matrix = NULL;
  public:
    Matrix(int);
    Matrix(int, vector&lt;Complex&gt;);
    Matrix();
    bool checkDom(Matrix, Matrix);
    int size();
    void size(unsigned int);
  </code></pre>
  
  <p>Here is my constructor for the Matrix, which copies values of type Complex into each element.</p>
  
  <pre><code>Matrix::Matrix(int sizer, vector&lt;Complex&gt; inputList) {
  
    sized = sizer;
  
    //Init all to 0+0i
    Complex** matrix = new Complex*[sizer];
    for (int i = 0; i &lt; sizer; ++i)
        matrix[i] = new Complex[sizer];
  
    int count = 0;
  
    //Copy vector values into matrix
    for (int i = 0; i &lt; sized; i++) {
      for (int j = 0; j &lt; sized; j++) {
          matrix[i][j] = inputList[count];
          count++;
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>If I insert a cout statement within this constructor, the matrices elements will print correctly:</p>
  
  <pre><code>//inside of constructor, prints all elements without a problem
  for (int i = 0; i &lt; sized; i++) {
          for (int j = 0; j &lt; sized; j++) {
              os &lt;&lt; right &lt;&lt; setw(6) &lt;&lt; matrix[i][j];
          }
              os &lt;&lt; endl;
      }
  </code></pre>
  
  <p>However, while operator overloading the >> operator to print the matrix, it crashes (no error at compile time).</p>
  
  <pre><code>friend ostream &amp;operator&lt;&lt;(ostream &amp;os, Matrix &amp;matprint){
      for (int i = 0; i &lt; matprint.sized; i++) {
          for (int j = 0; j &lt; matprint.sized; j++) {
              os &lt;&lt; right &lt;&lt; setw(6) &lt;&lt; matprint.matrix[i][j];
          }
              os &lt;&lt; endl;
      }
      return os;
  }
  </code></pre>
  
  <p>It seems to happen whenever I want to send a matrix element to the output stream using dot notation. I get the error</p>
  
  <p>Unhandled exception at 0x000E8943 in ConsoleApplication7.exe: 0xC0000005: Access violation reading location 0x00000000. </p>
  
  <p>My debugger also lists the matprint.matrix value as 0x00000000. I'm having trouble figuring out exactly where my reference goes wrong! Thanks!</p>
  
  <p>This is where the operator is invoked, in main:</p>
  
  <pre><code>Matrix  mat2(2, mat_vals);
  cout &lt;&lt; mat2;
  </code></pre>