void *realloc(void *ptr, size_t size)

C 标准库 - <stdlib.h> C 标准库 - <stdlib.h>

描述

C 库函数 void *realloc(void *ptr, size_t size) 尝试重新调整之前调用 malloccalloc 所分配的 ptr 所指向的内存块的大小。

声明

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

void *realloc(void *ptr, size_t size)

参数

返回值

该函数返回一个指针 ,指向重新分配大小的内存。如果请求失败,则返回 NULL。

实例

下面的实例演示了 realloc() 函数的用法。

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char *str;

   /* 最初的内存分配 */
   str = (char *) malloc(15);
   strcpy(str, "w3xue");
   printf("String = %s,  Address = %u\n", str, str);

   /* 重新分配内存 */
   str = (char *) realloc(str, 25);
   strcat(str, ".cc");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);
   
   return(0);
}

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

String = w3xue, Address = 355090448
String = example.com, Address = 355090448

C 标准库 - <stdlib.h> C 标准库 - <stdlib.h>