执行时(运行时)的内存分配称为动态内存分配。
动态内存的功能calloc()和malloc()支持。
当函数返回值并将其分配给指针变量时,可以通过使用这些函数来动态分配内存空间。
在这种情况下,仅当程序单元处于活动状态时才分配变量。
它使用称为堆的数据结构来实现动态分配。
有内存可重用性,不需要时可以释放内存。
效率更高。
在这种内存分配方案中,执行速度比静态内存分配慢。
在此过程中,可以随时释放内存。
以下程序使用动态内存分配函数计算一组元素中的偶数和奇数之和-
#include<stdio.h> #include<stdlib.h> void main(){ //Declaring variables, pointers// int i,n; int *p; int even=0,odd=0; //Declaring base address p using malloc// p=(int *)malloc(n*sizeof(int)); //Reading number of elements// printf("输入元素数: "); scanf("%d",&n); /*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/ if (p==NULL){ printf("Memory not available"); exit(0); } //Storing elements into location using for loop// printf("The elements are : \n"); for(i=0;i<n;i++){ scanf("%d",p+i); } for(i=0;i<n;i++){ if(*(p+i)%2==0){ even=even+*(p+i); }else{ odd=odd+*(p+i); } } printf("The sum of even numbers is : %d\n",even); printf("The sum of odd numbers is : %d\n",odd); }输出结果
输入元素数: 4 The elements are : 35 24 46 12 The sum of even numbers is : 82 The sum of odd numbers is : 35