
问题
使用C编程,使用动态分配的内存找到用户输入的n个数字的和。
解决方案
动态内存分配使C程序员能够在运行时分配内存。
我们用来在运行时动态分配内存的不同函数包括:
- malloc() - 在运行时分配一块内存。
- calloc() - 在运行时分配连续的内存块。
- realloc() - 用于减少(或扩展)已分配的内存。
- free() - 释放先前分配的内存空间。
以下C程序用于显示元素并计算n个数字的和。
采用微软 ASP.NET2.0(C#) 设计,使用分层设计模式,页面高速缓存,是迄今为止国内最先进的.NET语言企业网站管理系统。整套系统的设计构造,完全考虑大中小企业类网站的功能要求,网站的后台功能强大,管理简捷,支持模板机制。使用国际编码,通过xml配置语言,一套系统可同时支持任意多语言。全站可生成各类模拟静态。使用页面高速缓存,站点访问速度快。帐号密码都是: admin333【注意网站目录要
立即学习“C语言免费学习笔记(深入)”;
使用动态内存分配函数,我们试图减少内存的浪费。
示例
演示
#include#include 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
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
",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










