目录

void *realloc(void *ptr, size_t size)

描述 (Description)

C库函数void *realloc(void *ptr, size_t size)尝试调整先前通过调用malloccalloc分配的ptr指向的内存块。

声明 (Declaration)

以下是realloc()函数的声明。

void *realloc(void *ptr, size_t size)

参数 (Parameters)

  • ptr - 这是指向先前分配有要重新分配的malloc,calloc或realloc的内存块的指针。 如果为NULL,则分配新块,并由函数返回指向它的指针。

  • size - 这是内存块的新大小,以字节为单位。 如果它为0并且ptr指向现有的内存块,则释放由ptr指向的内存块并返回NULL指针。

返回值 (Return Value)

此函数返回指向新分配的内存的指针,如果请求失败则返回NULL。

例子 (Example)

以下示例显示了realloc()函数的用法。

#include <stdio.h>
#include <stdlib.h>
int main () {
   char *str;
   /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "iowiki");
   printf("String = %s,  Address = %u\n", str, str);
   /* Reallocating memory */
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);
   free(str);
   return(0);
}

让我们编译并运行上面的程序,它将产生以下结果 -

String = iowiki, Address = 355090448
String = iowiki.com, Address = 355090448
↑回到顶部↑
WIKI教程 @2018