Use of realloc() in C


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("
Error! memory not allocated.");       exit(0);    }    printf("
Enter elements of array : ");    for(i = 0; i < n; ++i) {       scanf("%d", p + i);       s += *(p + i);    }    printf("
Sum : %d", s);    p = (int*) realloc(p, 6);    printf("
Enter elements of array : ");    for(i = 0; i < n; ++i) {       scanf("%d", p + i);       s += *(p + i);    }    printf("
Sum : %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("
Enter elements of array : "); for(i = 0; i < n; ++i) {    scanf("%d", p + i);    s += *(p + i); }

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements