使用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("输入元素数: ");
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 : \n");
for(i=0;i<numofe;i++){
scanf("%d",p+i);
sum=sum+*(p+i);
}
printf("\nThe sum of elements is %d",sum);
free(p);//Erase first 2 memory locations//
printf("\nDisplaying the cleared out memory location : \n");
for(i=0;i<numofe;i++){
printf("%d\n",p[i]);//Garbage values will be displayed//
}
}输出结果输入元素数: 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