Let's start with the code:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int** matrix;
int n = 5;
int m = 5;
matrix = (int**)malloc(n*sizeof(int*));
for (int i = 0; i < n; i++) {
matrix[i] = (int*)malloc(m*sizeof(int*));
}
//This works:
matrix[4][90] = 50;
printf("%d", matrix[4][90]);
//This produces an error:
//matrix[5][90] = 50;
//printf("%d", matrix[5][90]);
return 0;
}
I've been using this method to dynamically allocate memory for a 2d array (and I've seen a lot of people use it too) and it works great. However, recently I noticed that it seems to allocate more memory than intended and I can't understand why.
In the above example, I'm trying to create a 5x5 array. It creates exactly 5 rows (n) and gives you an error if you try to access any other than those rows. Working as intended. Great! However, it seems like it's creating a massive number of columns (m), when I only want it to create 5. Why is this, and how do I fix it?
Same thing seems to be true for calloc as well.
Thanks!