[C] 动态数组的实现 →→→→→进入此内容的聊天室

来自 , 2019-11-24, 写在 C, 查看 105 次.
URL http://www.code666.cn/view/2321994d
  1. /* 动态数组的实现 */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. /* 分配数组 */
  6. void * alloc_array(void * p, const int n, const int size) {
  7.         p = malloc(size * n);
  8.         if (NULL == p) {
  9.                 printf("Error when allocting memory.\n");
  10.                 exit(0);
  11.         }
  12.         memset(p, 0, size * n); /* 将数组空间清0 */
  13.         return p;
  14. }
  15.  
  16. /* 释放数组 */
  17. void free_array(void * p) {
  18.         free(p);
  19.         p = NULL;
  20. }
  21.  
  22. int main(void) {
  23.         int * p = NULL;
  24.         int n = 5;
  25.         int i = 0;
  26.  
  27.         /* 使用alloc_array函数为p从堆上分配一个数组空间 */
  28.         p = (int *) alloc_array(p, n, sizeof(int));
  29.  
  30.         /* 使用循环语句从标准输入为数组赋值 */
  31.         printf("Please input %d numbers:\n", n);
  32.         for (i = 0; i < n; ++i)
  33.                 scanf("%d", &p[i]);
  34.  
  35.         /* 输出数组元素内容 */
  36.         printf("Print the element in this array:\n");
  37.         for (i = 0; i < n; ++i)
  38.                 printf("%4d", p[i]);
  39.         printf("\n");
  40.  
  41.         free_array(p);
  42.         return 0;
  43. }
  44.  

回复 "动态数组的实现"

这儿你可以回复上面这条便签

captcha