C - Write calloc, by calling malloc or by modifying it

怼烎@ 2023-01-13 06:28 185阅读 0赞

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net

  1. /*
  2. * The standard library function calloc(n,size) returns a pointer to n objects of
  3. * size size, with the storage initialized to zero.
  4. * Write calloc, by calling malloc or by modifying it.
  5. *
  6. * CAlloc.c - by FreeMan
  7. */
  8. #include <stdlib.h>
  9. #include <string.h>
  10. void *mycalloc(size_t nmemb, size_t size)
  11. {
  12. void *Result = NULL;
  13. /* use malloc to get the memory */
  14. Result = malloc(nmemb * size);
  15. /* and clear the memory on successful allocation */
  16. if (NULL != Result)
  17. {
  18. memset(Result, 0x00, nmemb * size);
  19. }
  20. /* and return the result */
  21. return Result;
  22. }
  23. #include <stdio.h>
  24. int main(void)
  25. {
  26. int *p = NULL;
  27. int i = 0;
  28. p = mycalloc(100, sizeof * p);
  29. if (NULL == p)
  30. {
  31. printf("mycalloc returned NULL.\n");
  32. }
  33. else
  34. {
  35. for (i = 0; i < 100; i++)
  36. {
  37. printf("%08X ", p[i]);
  38. if (i % 8 == 7)
  39. {
  40. printf("\n");
  41. }
  42. }
  43. printf("\n");
  44. free(p);
  45. }
  46. return 0;
  47. }
  48. // Output:
  49. /*
  50. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
  51. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
  52. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
  53. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
  54. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
  55. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
  56. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
  57. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
  58. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
  59. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
  60. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
  61. 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
  62. 00000000 00000000 00000000 00000000
  63. */

发表评论

表情:
评论列表 (有 0 条评论,185人围观)

还没有评论,来说两句吧...

相关阅读