realloc() – C语言库函数
C库函数 void *realloc(void *ptr, size_t size) 试图调整以前分配与调用malloc或calloc的ptr所指向的内存块的大小。
声明
以下是realloc() 函数的声明。
void*realloc(void*ptr,size_t size)
参数
-
ptr -- 这是以前用malloc,calloc或realloc分配,重新分配的内存块的指针。如果是NULL,分配一个新的块,由该函数返回一个指向它的指针。
-
size -- 这是新的内存块的大小(以字节为单位)。如果它是0 并且ptr 指向现有的内存块,指针所指向的内存块被释放,并返回一个NULL指针。
返回值
这个函数返回一个新分配的内存的指针,或NULL如果请求失败。
例子
下面的例子显示 realloc() 函数的用法。
#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