
问题
使用C编程,使用动态分配的内存找到用户输入的n个数字的和。
解决方案
动态内存分配使C程序员能够在运行时分配内存。
我们用来在运行时动态分配内存的不同函数包括:
malloc() – 在运行时分配一块内存。calloc() – 在运行时分配连续的内存块。realloc() – 用于减少(或扩展)已分配的内存。free() – 释放先前分配的内存空间。
以下C程序用于显示元素并计算n个数字的和。
立即学习“C语言免费学习笔记(深入)”;
使用动态内存分配函数,我们试图减少内存的浪费。
示例
演示
#include#includevoid 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 : 5Enter the elements :2334123456The sum of elements is 159Displaying the cleared out memory location :12522624012517712056
以上就是用一个例子解释C语言中的动态内存分配的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444718.html
微信扫一扫
支付宝扫一扫