c - malloc中sizeof的使用

标签 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?

现在我不需要转换结果了。但我不明白的是在没有 sizeof 运算符的情况下使用 malloc(size) 。例如,要创建一个矩阵,可以说 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);

mallocman 说:

The malloc() function allocates size bytes and returns a pointer to the allocated memory.

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

最佳答案

由于 ec_malloc() 不接受数据类型参数,因此它假设您将自己执行 sizeof(datatype) * size 。因此参数unsigned int size应该以字节为单位。

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

关于c - malloc中sizeof的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23328349/

相关文章:

c - 在 gcc 4.8 版本中, 'var' 的地址将始终计算为 'true'

c - 使用指向 char 的指针时如何使用 snprintf

将 C 数组中的元素复制到另一个数组中

python - VSTACK scipy.sparse.csr.csr_matrix 到一个 csr 矩阵

c++ - 为什么我在 OpenGL 的透视投影中将 Z 除以 W?

python - 填充numpy数组中的相邻元素

python - PyErr_CheckSignals 没有接收到信号

c - 在 C 的另一个结构中初始化和访问嵌套的 struct char 指针

c++ - 在头文件中将变量声明为指针和非指针的区别

对 C 中的指针和泛型(void)指针感到困惑