【发布时间】:2014-04-27 20:05:15
【问题描述】:
我正在尝试将矩阵的创建包装到一个函数中,但是在尝试理解从书中提取的以下代码 sn-p 时遇到问题:
// 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 说:
malloc() 函数分配 size 个字节并返回一个指向已分配内存的指针。
让size 为4,然后在ptr = malloc(size) 中分配4 个字节,但如果矩阵是int 类型。我不需要sizeof int * 4 吗?因为现在我认为我没有为整数矩阵分配足够的内存。
【问题讨论】:
-
这没有意义。为什么要从
malloc()包装器返回void **?sizeof有什么问题?如果你知道你必须使用它来保证正确性,那你为什么不使用它呢? -
那本书充满了它。
malloc(),至少现在,需要size_t参数,而不是int。
标签: c pointers matrix malloc sizeof