我正在尝试将矩阵的创建包装到函数中,但是我在尝试理解从书中提取的以下代码片段时遇到了问题:
// 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()函数分配大小字节并返回指向已分配内存的指针。
让malloc
为size
,然后在4
我分配4个字节,但矩阵的类型为ptr = malloc(size)
。我不需要int
吗?因为现在我认为我没有为整数矩阵分配足够的内存。
答案 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 )
。