Creating an 2D array using pointer/malloc, and then print it out I am trying to write 2 functions, one to read the matrix (2D array) and other one to print it out. So far I have:

/* Read a matrix: allocate space, read elements, return pointer. The
   number of rows and columns are given by the two arguments. */
double **read_matrix(int rows, int cols){

    double **mat = (double **) malloc(sizeof(double *)*rows);
    int i=0;
    for(i=0; i&lt;rows; i++){
    /* Allocate array, store pointer  */
    mat[i] = (double *) malloc(sizeof(double)*cols); 
   //what to do after??

     return mat;
}


then the print matrix function, not sure if it is correct

 void print_matrix(int rows, int cols, double **mat){
  for(i=0; i&lt;rows; i++){    /* Iterate of each row */
    for(j=0; j&lt;cols; j++){  /* In each row, go over each col element  */
    printf("%f ",mat[i][j]); /* Print each row element */
}
}}


and here is the main function I am using to run:

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;


double **read_matrix(int rows, int cols);
void print_matrix(int rows, int cols, double **mat);
void free_matrix(int rows, double **mat);

int main(){

  double **matrix;
  int rows, cols;
  /* First matrix */
  printf("Matrix 1\n");
  printf("Enter # of rows and cols: ");
  scanf("%d %d",&amp;rows,&amp;cols);
  printf("Matrix, enter %d reals: ",rows*cols);
  matrix = read_matrix(rows,cols); 
  printf("Your Matrix\n");  /* Print the entered data */
  print_matrix(rows,cols,matrix);
  free_matrix(rows, matrix);   /* Free the matrix */

    return 0;}
It seems OK to me as far as it goes. A couple of suggestions though:


read_matrix may be better split up into two functions, one to create it and the other to read the contents from the source, even if the create_matrix function is called from read_matrix - and you need to be aware of the possibility that the allocation may fail.
On the other hand, you may wish to consider just allocating a single block of size rows*cols of memory, and indexing it via y*rows + x rather than allocating several smaller blocks.
For 'neatness', you should consider using calloc( number_of_elements, sizeof (double) ) instead of malloc, just to give a (possibly) sensible initial value.
print_matrix could do with some layout changes, such that each row is on a separate line, and the corresponding cells line up under each other, something like %10.3f (but would depend on the type of data expected).