C 標(biāo)準(zhǔn)庫 - <stdlib.h>
C 庫函數(shù) void *realloc(void *ptr, size_t size) 嘗試重新調(diào)整之前調(diào)用 malloc 或 calloc 所分配的 ptr 所指向的內(nèi)存塊的大小。
下面是 realloc() 函數(shù)的聲明。
void *realloc(void *ptr, size_t size)
該函數(shù)返回一個指針 ,指向重新分配大小的內(nèi)存。如果請求失敗,則返回 NULL。
下面的示例演示了 realloc() 函數(shù)的用法。
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *str; /* 最初的內(nèi)存分配 */ str = (char *) malloc(15); strcpy(str, "nhooo"); printf("String = %s, Address = %p\n", str, str); /* 重新分配內(nèi)存 */ str = (char *) realloc(str, 25); strcat(str, ".com"); printf("String = %s, Address = %p\n", str, str); free(str); return(0); }
讓我們編譯并運行上面的程序,這將產(chǎn)生以下結(jié)果:
String = nhooo, Address = 0x7fa2f8c02b10 String = (cainiaoplus.com), Address = 0x7fa2f8c02b10