
malloc()函数代表内存分配,动态分配一块内存。
它保留指定大小的内存空间,并返回指向内存位置的空指针。
malloc() 函数携带垃圾值。返回的指针是void类型。
malloc()函数的语法如下 -
立即学习“C语言免费学习笔记(深入)”;
ptr = (castType*) malloc(size);
示例
以下示例展示了 malloc() 函数的用法。
现场演示
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char *MemoryAlloc;
/* memory allocated dynamically */
MemoryAlloc = malloc( 15 * sizeof(char) );
if(MemoryAlloc== NULL ){
printf("Couldn't able to allocate requested memory</p><p>");
}else{
strcpy( MemoryAlloc,"TutorialsPoint");
}
printf("Dynamically allocated memory content : %s</p><p>", MemoryAlloc);
free(MemoryAlloc);
}输出
当执行上述程序时,会产生以下结果 -
Dynamically allocated memory content: TutorialsPoint











