我试图将矩阵的创建包装到一个函数中,但在尝试理解从书中提取的以下代码片段时遇到问题:
// 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);
malloc
的 man
说:
The malloc() function allocates size bytes and returns a pointer to the allocated memory.
让size
为4
,然后在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/