title: C: Using a 2D array created in a function during main
body: <p>I have looked through similarly worded questions and had no luck with my problem.
  I am aiming to read in a matrix from a text file in C, and then perform operations on it. Currently, I am writing a function to read in the matrix. The text files always have the format</p>
  <pre><code># Comment
  # Comment
  matrix NROWS NCOLS
  DATA DATA DATA
  DATA DATA DATA etc
  end
  </code></pre>
  <p>so for a 3x4 matrix:</p>
  <pre><code># Comment
  # Comment
  matrix 3 4
  7.16669652013   8.21223145665   8.78374366033   5.87828106521   
  7.32124040244   4.30552353817   1.67905652974   3.91825198378   
  7.28717047595   3.83999063812   5.53693148121   6.03363152874
  end
  </code></pre>
  <p>My function currently is:</p>
  <pre class="lang-c prettyprint-override"><code>void read_matrix(char *filename, int rows, int cols) {
      char *status;
      char line[MAX_FILE_LINE_SIZE];
      int line_no = 1;
      char *data_line;
      double matrix[rows][cols];
  
      printf(&quot;Reading Matrix...\n&quot;);
      FILE *inf = fopen(filename, &quot;r&quot;);
      if (!inf) {
          fprintf(stderr, &quot;Error, could not open file '%s'\n&quot;, filename);
          exit(1);
      }
      
      status = fgets(line, sizeof(line), inf);
      while (status) {
          status = fgets(line, sizeof(line), inf);
          ///printf(&quot;%i: %s&quot;, line_no, line);
          if (line_no &gt;= 3 &amp;&amp; line_no &lt; 3+rows) {
              int i=0;
              data_line = strtok(line, &quot; \t&quot;);
              while (data_line != NULL) {
                  matrix[line_no-3][i] = atof(data_line);
                  data_line = strtok(NULL, &quot; \t&quot;);
                  i++;
              }
          }
          line_no ++;
      }
      printf(&quot;PRINT MATRIX\n&quot;);
      for (int z=0; z&lt;rows; z++) {
          for (int j=0; j&lt;cols; j++) {
              printf(&quot;matrix[%i][%i] = %f\n&quot;,z, j, matrix[z][j]);
          }
      }
      fclose(inf);
  }
  </code></pre>
  <p>which works great, and so at the end of the function I have all the data saved into a 2D array <code>matrix[rows][cols]</code>.
  However I am completely stumped on how to then use this function in main, as outside of the function the variable is no longer in scope. Any help would be very appreciated.</p>