Created
November 22, 2020 14:12
-
-
Save graphoarty/e7c8cc8600836c9c82df64665339719c to your computer and use it in GitHub Desktop.
Dynamically Allocate Matrix in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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