I am trying to define a function to return a square matrix (NxN) in C language:
#define true 1
#define false 0
typedef char bool;
typedef bool** Matrix;
Matrix matrix_alloc(int size)
{
Matrix matrix = (bool **) malloc(sizeof(bool) * size);
int i;
for (i = 0; i < size; i++) {
matrix[i] = (bool *) calloc(size, sizeof(bool));
}
return matrix;
}
void matrix_print(Matrix matrix, int size)
{
int i, j;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
printf("%i ", matrix[i][j]);
}
printf("\n");
}
}
However, it seems calloc()
isn't initializing the "cells" with zero as expected. I was told calloc
was safe for initialization, so I believe there is hole in my logics. Here is the output when running the two functions (e.g. to create a 9x9 matrix):
48 77 104 0 72 77 104 0 96
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
Wrong size in allocation: matrix
is a pointer to bool *
, not to bool
.
Avoid mistakes, size to the de-referenced pointer, not the type.
The cast is not needed in C, and should be omitted.
// too small
// Matrix matrix = (bool **) malloc(sizeof(bool) * size);
Matrix matrix = malloc(sizeof *matrix * size);