动态内存分配之11.1

/*
 * 请你自己尝试编写 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;
}


作者: Mrt-l   发布时间: 2010-11-28