C - Write calloc, by calling malloc or by modifying it
分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net
/*
* The standard library function calloc(n,size) returns a pointer to n objects of
* size size, with the storage initialized to zero.
* Write calloc, by calling malloc or by modifying it.
*
* CAlloc.c - by FreeMan
*/
#include <stdlib.h>
#include <string.h>
void *mycalloc(size_t nmemb, size_t size)
{
void *Result = NULL;
/* use malloc to get the memory */
Result = malloc(nmemb * size);
/* and clear the memory on successful allocation */
if (NULL != Result)
{
memset(Result, 0x00, nmemb * size);
}
/* and return the result */
return Result;
}
#include <stdio.h>
int main(void)
{
int *p = NULL;
int i = 0;
p = mycalloc(100, sizeof * p);
if (NULL == p)
{
printf("mycalloc returned NULL.\n");
}
else
{
for (i = 0; i < 100; i++)
{
printf("%08X ", p[i]);
if (i % 8 == 7)
{
printf("\n");
}
}
printf("\n");
free(p);
}
return 0;
}
// Output:
/*
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000
*/
还没有评论,来说两句吧...