阐述 C 编程中的 malloc 函数
问题
编写一个 C 程序,使用动态内存分配函数显示和添加元素。
解决方案
在 C 中,库函数 malloc 会在运行时以字节为单位分配内存块。它返回一个无类型指针,该指针指向所分配内存的基地址,并且会将内存保留为未初始化状态。
语法
void *malloc (size in bytes)
例如:
int *ptr;
ptr = (int * ) malloc (1000);
int *ptr;
ptr = (int * ) malloc (n * sizeof (int));
注意 − 如果内存未释放,则返回 NULL。
示例
#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 45 65 12 23 The sum of elements is 168 Displaying the cleared out memory location : 10753152 0 10748240 0 23
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP