使用示例说明 C 中的动态内存分配
问题
查找用户输入的 n 个数字的和,使用 C 编程动态分配内存。
解决方案
动态内存分配允许 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 : 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP