title: How do I pass a 2D array by reference?
body: <p>I'm reading the pixels from a plaintext .pgm file and I dynamically allocate an array to hold the pixels once they've been read, but it seems that the data inside is lost when my <code>readPGM</code> function ends. I'm passing an <code>int**</code> into a function, where becomes a 2D array and is filled, but it loses its values after the <code>readPGM</code> function ends. I suspect that passing the <code>int** pixels</code> by reference would help, but I'm not sure how to approach the problem and would appreciate any advice.</p>
  
  <pre><code>#Function called from within readPGM to allocate an array
  int** allocate_m(int rows, int cols){
      int **matrix;
      int i;
  
      matrix = (int **)malloc(sizeof(int *) * rows);
  
      for (i = 0; i &lt; rows; ++i) {
          matrix[i] = (int *)malloc(sizeof(int) * cols);
      }
      return matrix;
  }
  
  void readPGM(char* path, char version[3], int* cols, int* rows, int* grays, int** array){
      FILE* pgm;
      int pixel;
      int count = 0;
      pgm = fopen(path,"r");
  
      //Reading the header of the file
      fgets(version,3,pgm);
      fscanf(pgm,"%d %d",&amp;*cols,&amp;*rows);
      fscanf(pgm,"%d",&amp;*grays);
  
      //Allocating and filling the array of pixels
      array = allocate_m(*rows,*cols);
      while (fscanf(pgm,"%d",&amp;pixel) == 1){
          array[count/(*cols)][count%(*cols)] = pixel;
          count++;
      }
      fclose(pgm);
  }
  
  int main(void) {
      int cols, rows, grays;
      char version[3];
      int** pixels;
      readPGM("/home/charlie/25.pgm", version, &amp;cols, &amp;rows, &amp;grays, pixels);
      return 0;
  }
  </code></pre>
  
  <p>EDIT: Corrected <code>readPGM</code> function:</p>
  
  <pre><code>int** readPGM(char* path, char version[3], int* pcols, int* prows, int* pgrays) {
      FILE* pgm = fopen(path,"r");
      int pixel;
      int count = 0;
      fgets(version, 3, pgm);
      fscanf(pgm, "%d %d", pcols, prows);
      fscanf(pgm, "%d" ,pgrays);
  
      int rows=*prows, cols=*pcols;
  
      int** array = allocate_m(rows,cols);
  
      while (fscanf(pgm,"%d",&amp;pixel) == 1){
          array[count/cols][count%cols] = pixel;
          count++;
      }
      fclose(pgm);
      return array;
  }
  </code></pre>