在malloc中使用sizeof

时间:2014-04-27 20:05:15

标签: c pointers matrix malloc sizeof

我正在尝试将矩阵的创建包装到函数中,但是我在尝试理解从书中提取的以下代码片段时遇到了问题:

  // An error checked malloc() wrapper function
  void *ec_malloc(unsigned int size) {
     void *ptr;
     ptr = malloc(size);
     if(ptr == NULL)
        fatal("in ec_malloc() on memory allocation");
     return ptr;
  }

我已经检查了这个问题:

Do I cast the result of malloc?

现在我现在没有必要投出结果。但我不明白的是使用malloc(size)没有sizeof运算符。例如,要创建一个矩阵,让我们说int **matrix我也创建了这个函数:

  // An error checked malloc() wrapper function
  void **double_ec_malloc(unsigned int size) {
     void **ptr;
     ptr = malloc(size);
     if(ptr == NULL)
        fatal("in ec_malloc() on memory allocation");
     return ptr;
  }

然后我这样做:

  int **matrixA = double_ec_malloc(size);

  int i = 0;
  for (i = 0; i < size; i++){
    matrixA[i] = ec_malloc(size);

man的{​​{1}}说:

  

malloc()函数分配大小字节并返回指向已分配内存的指针。

mallocsize,然后在4我分配4个字节,但矩阵的类型为ptr = malloc(size)。我不需要int吗?因为现在我认为我没有为整数矩阵分配足够的内存。

2 个答案:

答案 0 :(得分:1)

由于ec_malloc()没有采用数据类型参数,因此它假设您自己会sizeof(datatype) * size。因此,参数unsigned int size应该以字节为单位。

请注意malloc()本身的行为方式。

答案 1 :(得分:0)

malloc函数(以及您的ec_malloc)都分配一个长度为size字节的线性字节区域。

sizeof只返回int,但它与malloc无任何关系(除了malloc经常使用之外)。

32位整数长度为4个字节。 sizeof(int)会返回4.如果您想要4个int的空间,可以说malloc( sizeof(int) * 4 )