C 语言中的动态内存分配是什么意思?


动态内存分配

  • 在执行(运行)中分配内存被称为动态内存分配。

  • 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("Enter the number of elements : ");
   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 : 
");    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
",even);    printf("The sum of odd numbers is : %d
",odd); }

输出

Enter the number of elements : 4
The elements are :
35
24
46
12
The sum of even numbers is : 82
The sum of odd numbers is : 35

更新于: 09-3-2021

12K+ 浏览量

开启你的事业

完成课程以获得认证

开始使用
广告
© . All rights reserved.