malloc() – C语言库函数
C库函数 void *malloc(size_t size) 分配请求的内存,并返回一个指向它的指针。
声明
以下是声明函数 malloc() 。
void*malloc(size_t size)
参数
-
size -- 这是内存块的大小(以字节为单位)。
返回值
这个函数返回一个指针分配的内存,或NULL如果请求失败。
例子
下面的例子显示了函数malloc() 的用法。
#include<stdio.h>#include<stdlib.h>int main(){char*str;/* Initial memory allocation */ str =(char*) malloc(15); strcpy(str,"yiibai"); printf("String = %s, Address = %u ", str, str);/* Reallocating memory */ str =(char*) realloc(str,25); strcat(str,".com"); printf("String = %s, Address = %u ", str, str); free(str);return(0);}
让我们编译和运行上面的程序,这将产生以下结果:
String = yiibai, Address = 355090448 String = xyhtml5.com, Address = 355090448