C语言中的malloc是什么?
C 库内存分配函数 void *malloc(size_t size) 分配请求的内存并返回指向它的指针。
内存分配函数
内存可以按照下面解释的两种方式分配:

一旦在编译时分配了内存,就不能在执行期间更改它。将存在内存不足或内存浪费的问题。
解决方法是在程序执行期间根据用户的需求动态创建内存。
用于动态内存管理的标准库函数如下:
- malloc ( )
- calloc ( )
- realloc ( )
- free ( )
Malloc() 函数
此函数用于在运行时以字节为单位分配内存块。它返回一个 void 指针,该指针指向已分配内存的基地址。
malloc() 的语法如下:
void *malloc (size in bytes)
示例 1
以下示例显示了 malloc() 函数的使用。
int *ptr; ptr = (int * ) malloc (1000); int *ptr; ptr = (int * ) malloc (n * sizeof (int));
注意 - 如果内存不为空闲,则返回 NULL。
示例程序
以下是演示动态内存分配函数 - malloc() 的 C 程序。
#include<stdio.h>
#include<stdlib.h>
void main(){
//Declaring variables and pointer//
int numofele,i;
int *p;
//Reading elements as I/p//
printf("Enter the number of elements in the array: ");
scanf("%d",&numofele);
//Declaring malloc function//
p = (int *)malloc(numofele * (sizeof(int)));
//Reading elements into array of pointers//
for(i=0;i<numofele;i++){
p[i]=i+1;
printf("Element %d of array is : %d
",i,p[i]);
}
}输出
执行上述程序时,会产生以下结果:
Enter the number of elements in the array: 4 Element 0 of array is : 1 Element 1 of array is : 2 Element 2 of array is : 3 Element 3 of array is : 4
示例 2
以下是使用动态内存分配函数显示元素的 C 程序:
前五个块应为空,后五个块应包含逻辑。
#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 : 12 10 24 45 67 The sum of elements is 158 Displaying the cleared out memory location : 7804032 0 7799120 0 67
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP