Use of realloc() in C

CProgrammingServer Side Programming

The function realloc is used to resize the memory block which is allocated by malloc or calloc before.

Here is the syntax of realloc in C language,

void *realloc(void *pointer, size_t size)

Here,

pointer − The pointer which is pointing the previously allocated memory block by malloc or calloc.

size − The new size of memory block.

Here is an example of realloc() in C language,

Example

 Live Demo

#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

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 memory block is allocated by calloc() and sum of elements is calculated. After that, realloc() is resizing the memory block from 4 to 6 and calculating 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);
}
raja
Updated on 26-Jun-2020 07:58:12

Advertisements