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