C 語言中關於動態記憶體分配函式的示例程式
問題
如何使用 C 語言中的動態記憶體分配函式顯示和計算 n 個數字的總和?
解決方案
以下是 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: 4 Enter the elements: 23 45 67 89 The sum of elements is 224 Displaying the cleared out memory location: 7410816 0 7405904 0
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP