- ถ้าทำงานสำเร็จ โปรแกรมจะคืนพอร์ยเตอร์ ptr ที่มีขนาด size
- ถ้าไม่สามารถขยายต่อไปได้ realloc จะหาพื้นที่ใหม่ที่สามารถจองให้ได้ตามขนาดของ size จากนั้นจะคำการคัดลอกข้อมูลเก่าของ ptr ไปไว้ที่พื้นที่ใหม่ และคืนค่าพอร์ยเตอร์ ณ พื้นที่ใหม่นั้น และทำการปลดปล่อยพื้นที่เก่า free()
- ถ้า ptr เป็น NULL . realloc จะทำงานเหมือนกับ malloc
- ถ้า size = 0 . realloc จะทำการ free() พื้นที่ที่ ptr พอร์ยอยู่ และคืนค่า NULL
- ถ้าไม่สามารถขยายพื้นที่ได้ หรือไม่สามารถหาพื้นที่ใหม่ได้ realloc คืนค่า NULL และพื้นที่เก่าไม่มีการเปลี่ยนแปลง
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int main(void) | |
{ | |
char str[] = "123456"; | |
char *p = NULL; | |
p = (char *) realloc(p,strlen(str) + 1); | |
strcpy(p,str); | |
p = (char *) realloc(p,strlen(p) + strlen(str) + 1); | |
strcat(p,str); | |
printf("%s",p); | |
return 0; | |
} |