title: Read a file into a multidimensional array with dynamic allocation in C
body: <p>How can I read the data from a file with structure like the one below into a multidimensional array of integers in C?</p>
  
  <p>file:</p>
  
  <pre><code>3 4 30 29
  23 43 4 43
  </code></pre>
  
  <p>I need put this inside of an "int** matrix" variable using dynamic allocation.</p>
  
  <p>UPDATED:</p>
  
  <p>I want an example code which I can go over and study the relation between the functionalities listed below:</p>
  
  <ul>
  <li>multidimensional arrays and their relation with pointer-to-pointer;</li>
  <li>dynamic allocation of memory and some explanation about it's use;</li>
  <li>how to deal with data coming from an external source that we don't know the size of, how separate the rows/cols into our array inside of the C program.</li>
  </ul>
  
  <p>SHARING CODE:</p>
  
  <pre><code>int** BuildMatrixFromFile(char* infile, int rows, int cols){
  
      FILE *fpdata;   //  deal with the external file
      int** arreturn; //  hold the dynamic array
      int i,j;        //  walk thru the array 
  
      printf("file name: %s\n\n", infile);
  
      fpdata = fopen(infile, "r");    //  open file for reading data
  
      arreturn = malloc(rows * sizeof(int *));
      if (arreturn == NULL)
      {
          puts("\nFailure trying to allocate room for row pointers.\n");
          exit(0);
      }
  
      for (i = 0; i &lt; rows; i++)
      {
  
          arreturn[i] = malloc(cols * sizeof(int));
          if (arreturn[i] == NULL)
          {
              printf("\nFailure to allocate for row[%d]\n",i);
              exit(0);
          }
  
          for(j=0;j&lt;cols;++j)
              fscanf(fpdata, "%d", &amp;arreturn[i][j]);
  
      }
  
      fclose(fpdata); // closing file buffer
  
      return arreturn;    
  }
  </code></pre>
  
  <p>Thank you.</p>