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("输入元素数: ");
   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//
   }
}
输出结果

执行以上程序后,将产生以下结果-

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