卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章18486本站已运行341

用一个例子解释C语言中的动态内存分配

用一个例子解释C语言中的动态内存分配

问题

使用C编程,使用动态分配的内存找到用户输入的n个数字的和。

解决方案

动态内存分配使C程序员能够在运行时分配内存。

我们用来在运行时动态分配内存的不同函数包括:

  • malloc() - 在运行时分配一块内存。
  • calloc() - 在运行时分配连续的内存块。
  • realloc() - 用于减少(或扩展)已分配的内存。
  • free() - 释放先前分配的内存空间。

以下C程序用于显示元素并计算n个数字的和。

使用动态内存分配函数,我们试图减少内存的浪费。

示例

演示

'
#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables and pointers,sum//
   int numofe,i,sum=0;
   int *p;
   //Reading number of elements from user//
   printf("Enter the number of elements : ");
   scanf("%d",&numofe);
   //Calling malloc() function//
   p=(int *)malloc(numofe*sizeof(int));
   /*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);
   }
   //Printing elements//
   printf("Enter the elements : <p>");
   for(i=0;i<numofe;i++){
      scanf("%d",p+i);
      sum=sum+*(p+i);
   }
   printf("</p><p>The sum of elements is %d",sum);
   free(p);//Erase first 2 memory locations//
   printf("</p><p>Displaying the cleared out memory location : </p><p>");
   for(i=0;i<numofe;i++){
      printf("%d</p><p>",p[i]);//Garbage values will be displayed//
   }
}</p>

输出

'
Enter the number of elements : 5
Enter the elements :
23
34
12
34
56
The sum of elements is 159
Displaying the cleared out memory location :
12522624
0
12517712
0
56
卓越飞翔博客
上一篇: 为什么PHP在多用户商城系统开发中更优秀?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏