Reputation: 307
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
Upvotes: 0
Views: 124
Reputation: 152
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv, char **envp) {
int rows=3, cols=2, i, j;
char *myName = (char *) calloc(rows*cols, sizeof(char));
char chTemp = 'a';
//Kh
//al
//id
*(myName)='K'; *(myName+1)='h'; *(myName+2)='a'; *(myName+3)='l'; *(myName+4)='i'; *(myName+5)='d';
for(i=0; i<rows; i++){
for(j=0; j<cols; j++){
chTemp = *(myName+i*cols+j);
printf("%c", chTemp);
}
printf("\n");
}
return (EXIT_SUCCESS);
}
Upvotes: -1
Reputation: 154245
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);
Upvotes: 2