Skip to content

Instantly share code, notes, and snippets.

@graphoarty
Created November 22, 2020 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graphoarty/e7c8cc8600836c9c82df64665339719c to your computer and use it in GitHub Desktop.
Save graphoarty/e7c8cc8600836c9c82df64665339719c to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment