原型:extern void *malloc(unsigned int num_bytes);
用法:#include <malloc.h>
或#include<stdlib.h>
功能:用于向内存申请空间,分配长度为num_bytes字节的内存块
说明:如果分配成功则返回指向被分配内存的指针,否则返回空指针NULL。
当内存不再使用时,应使用free()函数将内存块释放。
以下是本人追加的讲解
因为malloc的返回值是void *
所以动态开辟后的内存都需要强制转换类型
例如开辟了10个int型内存空间
格式就是
int *p;
p=(int *)malloc(10*sizeof(int))
通用格式 指针=(数据指针类型)malloc(开辟个数*sizeof(数据类型))
例子
#include "stdafx.h"
#include <stdlib.h> /* For _MAX_PATH definition */
#include <stdio.h>
#include <malloc.h>
int main(int argc, char* argv[])
{
char *string;
/* Allocate space for a path name */
string = (char*)malloc( 10);
if( string == NULL )
printf( "Insufficient memory available\n" );
else
{
printf( "Memory space allocated for path name\n" );
free( string );
printf( "Memory freed\n" );
}
return 0;
}