Dynamically Allocate Matrix in C | A Helpful Line-by-Line Code Tutorial

Dynamically Allocate Matrix in C

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[]){

  int rows = 3;
  int cols = 3;

  // allocate memory to store pointers which point to each row
  int** matrix = (int **) malloc(rows * sizeof(int *));

  for(int i = 0; i < rows; i++){

    // allocate memory to store items in each column
    *(matrix + i) = malloc(cols * sizeof(int));

    for(int j = 0; j < rows; j++){

      // assign value to item in matrix
      *(*(matrix + i) + j) = i + j;

    }  

  }

  return 0;
}