C 庫(kù)函數(shù) - realloc()
C 標(biāo)準(zhǔn)庫(kù) - <stdlib.h>
描述
C 庫(kù)函數(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ù)
- ptr -- 指針指向一個(gè)要重新分配內(nèi)存的內(nèi)存塊,該內(nèi)存塊之前是通過(guò)調(diào)用 malloc、calloc 或 realloc 進(jìn)行分配內(nèi)存的。如果為空指針,則會(huì)分配一個(gè)新的內(nèi)存塊,且函數(shù)返回一個(gè)指向它的指針。
- size -- 內(nèi)存塊的新的大小,以字節(jié)為單位。如果大小為 0,且 ptr 指向一個(gè)已存在的內(nèi)存塊,則 ptr 所指向的內(nèi)存塊會(huì)被釋放,并返回一個(gè)空指針。
返回值
該函數(shù)返回一個(gè)指針 ,指向重新分配大小的內(nèi)存。如果請(qǐng)求失敗,則返回 NULL。
實(shí)例
下面的實(shí)例演示了 realloc() 函數(shù)的用法。
#include <stdio.h> #include <stdlib.h> int main() { char *str; /* 最初的內(nèi)存分配 */ str = (char *) malloc(15); strcpy(str, "w3cschool"); printf("String = %s, Address = %u\n", str, str); /* 重新分配內(nèi)存 */ str = (char *) realloc(str, 25); strcat(str, ".cn"); printf("String = %s, Address = %u\n", str, str); free(str); return(0); }
讓我們編譯并運(yùn)行上面的程序,這將產(chǎn)生以下結(jié)果:
String = w3cschool, Address = 355090448 String = w3cschool.cn, Address = 355090448
更多建議: