简体   繁体   中英

'calloc' on bidimensional array doesn't initialize properly

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 (eg 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);
#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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM