realloc ফাংশন মেমরি ব্লক রিসাইজ করতে ব্যবহৃত হয় যা আগে malloc বা calloc দ্বারা অ্যালোকেটেড ছিল।
সি ভাষায় realloc-এর সিনট্যাক্স:
void *realloc(void *pointer, size_t size)
এখানে,
- pointer −
mallocবাcallocদ্বারা আগে অ্যালোকেটেড মেমরি ব্লককে পয়েন্ট করার পয়েন্টার। - size − মেমরি ব্লকের নতুন আকার।
সি ভাষায় 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
উপরের প্রোগ্রামে মেমরি ব্লক calloc()-এ 의해 অ্যালোকেট করা হয়েছে এবং উপাদানগুলোর যোগফল ক্যালকুলেট করা হয়েছে। তারপর realloc() মেমরি ব্লক ৪ থেকে ৬ আকারে রিসাইজ করছে এবং তাদের যোগফল ক্যালকুলেট করছে।
p = (int*) realloc(p, 6); printf("\nEnter elements of array : "); for(i = 0; i < n; ++i) { scanf("%d", p + i); s += *(p + i); }