使用示例說明 C 中的動態記憶體分配
問題
查詢使用者輸入的 n 個數字的和,使用 C 程式設計動態分配記憶體。
解決方案
動態記憶體分配允許 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 :
");
for(i=0;i<numofe;i++){
scanf("%d",p+i);
sum=sum+*(p+i);
}
printf("
The sum of elements is %d",sum);
free(p);//Erase first 2 memory locations//
printf("
Displaying the cleared out memory location :
");
for(i=0;i<numofe;i++){
printf("%d
",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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP