您好,欢迎访问一九零五行业门户网

用一个例子解释C语言中的动态内存分配

问题使用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("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语言中的动态内存分配的详细内容。
其它类似信息

推荐信息