二维数组上的“ calloc”未正确初始化

问题描述

我正在尝试定义一个函数,以返回 C语言的方阵(NxN):

function showSinglePrice(agent) {    

    const item = agent.context.get("item"),place = item.parameters.place,size = item.parameters.size,type = item.parameters.type;

    return base(tablePlaces) //defined variable before this function
      .select({
        maxRecords: 1,//just want 1
        view: viewName,//defined variable before this function
        filterByFormula: `AND({type} = "${type}",{size} = "${size}",{place} = "${place}")`
      })
      .firstPage()
      .then(result => {
        
        console.log(result);

        var getPrice = result[0].fields.price;

        agent.add(`the current price is: $ ${getPrice}`); //its working
      })
      .catch(error => {
        console.log(error);

        response.json({
          fulfillmentMessages: [
            {
              text: {
                text: ["We got the following error..."] //will work on it
              }
            }
          ]
        });
      });
  }

但是,看来#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"); } } 并没有像预期的那样初始化为零的“单元格”。有人告诉我calloc()进行初始化是安全的,因此我认为我的逻辑存在漏洞。这是运行两个函数(例如创建9x9矩阵)时的输出

calloc

解决方法

分配的大小错误:matrix指向bool *,而不是bool的指针。

避免错误,避免引用的指针大小,而不是类型。

在C语言中不需要强制转换,因此应将其省略。

//                                  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);
}