English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The function realloc is used to adjust the size of the memory block previously allocated by malloc or calloc.
This is the syntax of realloc in C language.
void *realloc(void *pointer, size_t size)
here,
Pointer-a pointer to the previously allocated memory block pointed by malloc or calloc.
Size-the new size of the memory block.
this isrealloc()
C language example,
#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; }
Output result
Enter elements of array : 3 34 28 8 Sum : 73 Enter elements of array : 3 28 33 8 10 15 Sum : 145
In the above program, the storage block is allocated bycalloc()
and calculate the sum of elements. After that,realloc()
change the size of the storage block from4Adjust to6then calculate their sum.
p = (int*) realloc(p 6); printf("\nEnter elements of array: "); for(i = 0; i < n; ++i) { scanf("%d", p + i); s += *(p + i); }