Allocating Space for 2d Arrays with malloc()
Yet another post in my effort to be helpful. If you want to allocate space for a two dimensional array you need to be careful. Remember that a 2d array of floats is a float**, meaning a pointer to a block in memory which is a list of float pointers. Each of these float pointers is a pointer to an array of floats. If you want a couple functions to do this for you, you are in luck:
void allocate_matrix(float*** A, int n, int m) {
int i;
// Allocate storage for pointer array
*A = malloc(n * sizeof(float *));
if (A == NULL) {
printf("Error: malloc could not allocate %d bytes for a\n", n
* sizeof(float *));
return;
}
for (i = 0; i < n; i++) {
(*A)[i] = malloc(n * sizeof(float));
if ((*A)[i] == NULL) {
printf("Error: malloc could not allocate %d bytes for a\n", n
* sizeof(float));
return;
}
}
}
void free_matrix(float*** A, int n) {
int i;
for (i = 0; i < n; i++)
free((*A)[i]);
free(*A);
}
Remember that we need to take in a float*** because when we call the function we need to do this:
float** A; allocate_matrix(&A, n, m);
Otherwise our pointer is copied and lost due to out of scope. Don’t forget that you need to free your 2d array the same way. This method is useful because gcc and many compilers have a limit on how much space you can just statically allocate. I found I can’t get much bigger than a 1500×1500 array without seg faulting at runtime. You might be able to increase the maximum size but the ideal way is to allocate the memory yourself.
Hope this way useful.