/*
* 请你自己尝试编写 calloc 函数,函数内部使用 malloc 函数来获取内存。
*/
/* A function than performs the same job as the library 'calloc' function */
#include <stdlib.h> #include <stdio.h>
void *calloc( size_t n_elements, size_t element_size ) { char *new_memory;
n_elements *= element_size; // 获取字节数 //n_elements = n_elements * element_size; new_memory = malloc( n_elements ); if( new_memory != NULL ) { char *ptr;
ptr = new_memory; while( --n_elements >= 0 ) //在函数返回之前将动态获得的内存初始化为0 *ptr++ = '\0'; }
return new_memory; }
|
阅读(1213) | 评论(1) | 转发(0) |