我正在尝试将矩阵的创建包装到一个函数中,但是在尝试理解从书本中摘录的以下代码段时遇到了问题:
// 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;
}
我已经检查了这个问题:
现在,我现在没有必要强制转换结果。但是我不明白的是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
为malloc
:
malloc()函数分配大小字节,并返回指向分配的内存的指针。
让size
是4
,然后ptr = malloc(size)
我分配4个字节,但是如果matrix是type的话int
。我不需要sizeof int * 4
吗?因为现在我想我没有为整数矩阵分配足够的内存。
由于ec_malloc()
不采用数据类型参数,因此假定您会sizeof(datatype) * size
自己做。因此,参数unsigned int size
应以字节为单位。
请注意,它malloc()
本身就是如何表现的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句