首頁  >  文章  >  後端開發  >  用一個例子解釋C語言中的動態記憶體分配

用一個例子解釋C語言中的動態記憶體分配

王林
王林轉載
2023-09-09 08:53:06610瀏覽

用一個例子解釋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><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//
   }
}

輸出

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

以上是用一個例子解釋C語言中的動態記憶體分配的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除