If you want to create mxn matrix with malloc but not sure how, here's the way.
First of all, mxn matrix is m rows and n columns.
We can use double pointers to do this.
First you create memory space for m rows.
Then, you create memory space for n columns.
int ** mat;
mat = malloc(m * sizeof(int*)); // we are creating memory space for int pointers. This basically means 'we want to create memory space that can hold memory address that can hold array of columns
// each of mat at i'th index is the memory address for each row
// so we need to allocate memories for each row now
for (int i = 0; i < m; i++) {
mat[i] = malloc(n * sizeof(int));
}
Voila, we are done!
Top comments (0)