ฟังก์ชันการจัดสรรหน่วยความจำ C ไลบรารี่ void *realloc(void *ptr, size_t size) พยายามปรับขนาดบล็อกหน่วยความจำที่ชี้ไปโดย ptr ซึ่งก่อนหน้านี้ได้รับการจัดสรรด้วยการเรียก malloc หรือ calloc
ฟังก์ชันการจัดสรรหน่วยความจำ
หน่วยความจำสามารถจัดสรรได้สองวิธีตามที่อธิบายไว้ด้านล่าง -

เมื่อจัดสรรหน่วยความจำ ณ เวลาคอมไพล์แล้ว จะไม่สามารถเปลี่ยนแปลงได้ในระหว่างการดำเนินการ จะมีปัญหาเรื่องความไม่เพียงพอหรือการสูญเสียความจำอย่างอื่น
วิธีแก้ไขคือสร้างหน่วยความจำแบบไดนามิก เช่น ตามความต้องการของผู้ใช้ระหว่างการทำงานของโปรแกรม
ฟังก์ชันไลบรารีมาตรฐานที่ใช้สำหรับการจัดการหน่วยความจำแบบไดนามิกมีดังนี้ -
- malloc ( )
- calloc ( )
- realloc ( )
- ฟรี ( )
ฟังก์ชัน realloc ( )
-
ใช้สำหรับการจัดสรรหน่วยความจำใหม่
-
สามารถลดหรือเพิ่มหน่วยความจำที่จัดสรรได้
-
ส่งคืนตัวชี้เป็นโมฆะที่ชี้ไปยังที่อยู่ฐานของหน่วยความจำที่จัดสรรใหม่
ไวยากรณ์สำหรับฟังก์ชัน realloc() มีดังนี้ -
Free void *realloc (pointer, newsize);
ตัวอย่าง
ตัวอย่างต่อไปนี้แสดงการใช้งานฟังก์ชัน realloc()
int *ptr; ptr = (int * ) malloc (1000);// we can use calloc also - - - - - - - - - ptr = (int * ) realloc (ptr, 500); - - - - - - ptr = (int * ) realloc (ptr, 1500);
ตัวอย่าง
รับด้านล่างเป็นโปรแกรม C โดยใช้ฟังก์ชัน realloc () -
#include<stdio.h>
#include<stdlib.h>
int main(){
int *ptr, i, num;
printf("array size is 5\n");
ptr = (int*)calloc(5, sizeof(int));
if(ptr==NULL){
printf("Memory allocation failed");
exit(1); // exit the program
}
for(i = 0; i < 5; i++){
printf("enter number at %d: ", i);
scanf("%d", ptr+i);
}
printf("\nLet's increase the array size to 7\n ");
ptr = (int*)realloc(ptr, 7 * sizeof(int));
if(ptr==NULL){
printf("Memory allocation failed");
exit(1); // exit the program
}
printf("\n enter 2 more integers\n\n");
for(i = 5; i < 7; i++){
printf("Enter element number at %d: ", i);
scanf("%d", ptr+i);
}
printf("\n result array is: \n\n");
for(i = 0; i < 7; i++){
printf("%d ", *(ptr+i) );
}
return 0;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
array size is 5 enter number at 0: 23 enter number at 1: 12 enter number at 2: 45 enter number at 3: 67 enter number at 4: 20 Let's increase the array size to 7 enter 2 more integers Enter element number at 5: 90 Enter element number at 6: 60 result array is: 23 12 45 67 20 90 60