फ़ंक्शन realloc का उपयोग मेमोरी ब्लॉक को आकार देने के लिए किया जाता है जिसे पहले malloc या calloc द्वारा आवंटित किया जाता है।
यहाँ C भाषा में realloc का सिंटैक्स दिया गया है,
void *realloc(void *pointer, size_t size)
यहां,
सूचक - पॉइंटर जो पहले आवंटित मेमोरी ब्लॉक को मॉलोक या कॉलोक द्वारा इंगित कर रहा है।
आकार -मेमोरी ब्लॉक का नया आकार।
यहाँ C भाषा में realloc() का एक उदाहरण दिया गया है,
उदाहरण
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) calloc(n, sizeof(int));
if(p == NULL) {
printf("\nError! memory not allocated.");
exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
p = (int*) realloc(p, 6);
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
return 0;
} आउटपुट
Enter elements of array : 3 34 28 8 Sum : 73 Enter elements of array : 3 28 33 8 10 15 Sum : 145
उपरोक्त कार्यक्रम में, मेमोरी ब्लॉक को कॉलोक () द्वारा आवंटित किया जाता है और तत्वों के योग की गणना की जाती है। उसके बाद, realloc() मेमोरी ब्लॉक को 4 से 6 तक आकार दे रहा है और उनकी राशि की गणना कर रहा है।
p = (int*) realloc(p, 6);
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}