zoukankan      html  css  js  c++  java
  • c语言中动态数组的实现

    在数组一章中,曾介绍过数组的长度是预先定义好的,在整个程序中固定不变。C语言中不允许动态数组类型。例如: int n;scanf("%d",&n);int a[n];用变量表示长度,想对数组的大小作动态说明, 这是错误的。但是在实际的编程中,往往会发生这种情况,即所需的内存空间取决于实际输入的数据,而无法预先确定。对于这种问题,用数组的办法很难解决。为了解决上述问题,C语言提供了一些内存管理函数,这些内存管理函数可以按需要动态地分配内存空间,也可把不再使用的空间回收待用,为有效地利用内存资源提供了手段。其它文献中所提到的"动态数组",指的就是利用内存的申请和释放函数,在程序的运行过程中,根据实际需要指定数组的大小.其本质是一个指向数组的指针变量.常用的内存管理函数有以下三个:

      1.分配内存空间函数malloc

      调用形式: (类型说明符*) malloc (size) 功能:在内存的动态存储区中分配一块长度为"size"字节的连续区域。函数的返回值为该区域的首地址。“类型说明符”表示把该区域用于何种数据类型。(类型说明符*)表示把返回值强制转换为该类型指针。“size”是一个无符号数。例如:pc=(char *) malloc (100); 表示分配100个字节的内存空间,并强制转换为字符数组类型,函数的返回值为指向该字符数组的指针, 把该指针赋予指针变量pc。

      2.分配内存空间函数 calloc

      calloc 也用于分配内存空间。调用形式: (类型说明符*)calloc(n,size)功能:在内存动态存储区中分配n块长度为“size”字节的连续区域。函数的返回值为该区域的首地址。(类型说明符*)用于强制类型转换。calloc函数与malloc 函数的区别仅在于一次可以分配n块区域。例如: ps=(struet stu*) calloc(2,sizeof(struct stu)); 其中的sizeof(structstu)是求stu的结构长度。因此该语句的意思是:按stu的长度分配2块连续区域,强制转换为stu类型,并把其首地址赋予指针变量ps。

      3.释放内存空间函数free

      调用形式: free(void*ptr); 功能:释放ptr所指向的一块内存空间,ptr 是一个任意类型的指针变量,它指向被释放区域的首地址。被释放区应是由malloc或calloc函数所分配的区域。
    ----------------------------------------------------------------------------------------------------------------------------------

    // 程 式 名: DynamicArray.c
    // 作      者: Steven Wang
    // 程式功能: 动态数组的实现
    // 功能描述: 动态数组的创建与使用
    // 完成时间: 2006-11-22

    #include <stdio.h>
    #include <malloc.h>
    #include <stdlib.h>

    void main()
    {
         int *array = 0, num, i;
         printf("please input the number of element: ");
         scanf("%d", &num);

         // 申请动态数组使用的内存块
         array = (int *)malloc(sizeof(int)*num);
         if (array == 0)             // 内存申请失败,提示退出
         {
             printf("out of memory,press any key to quit...\n");
             exit(0);             // 终止程序运行,返回操作系统
         }

         // 提示输入num个数据
          printf("please input %d elements: ", num);
          for (i = 0; i < num; i++)
             scanf("%d", &array);

         // 输出刚输入的num个数据
         printf("%d elements are: \n", num);
         for (i = 0; i < num; i++)
             printf("%d,", array);

         printf("\b \n");    // 删除最后一个数字后的分隔符逗号
         free(array);        // 释放由malloc函数申请的内存块
    }
  • 相关阅读:
    16. 3Sum Closest
    17. Letter Combinations of a Phone Number
    20. Valid Parentheses
    77. Combinations
    80. Remove Duplicates from Sorted Array II
    82. Remove Duplicates from Sorted List II
    88. Merge Sorted Array
    257. Binary Tree Paths
    225. Implement Stack using Queues
    113. Path Sum II
  • 原文地址:https://www.cnblogs.com/buffer/p/1619163.html
Copyright © 2011-2022 走看看