Realloc() expands the memory allocated by calloc() or malloc() - C Memory

C examples for Memory:realloc

Description

Realloc() expands the memory allocated by calloc() or malloc()

Demo Code

#include<stdio.h> 
#include<stdlib.h> 
int main()//from   w w  w .  j  a  va2 s . c  o m
{
   int *number;
   int *newNumber;
   int x;
   number = (int *)malloc(sizeof(int) * 5);
   if (number == NULL) {
      printf("\nOut of memory!\n");
      return 1;
   }

   for (x = 0; x < 5; x++) {
      number[x] = x * 100;
      printf("number[%d] = %d\n", x, number[x]);
   }

   newNumber = (int *)realloc(number, 10 * sizeof(int));

   if (newNumber == NULL) {
      printf("\nOut of memory!\n");
      return 1;
   }
   else
      number = newNumber;

   for (x = 5; x < 10; x++)
      number[x] = x * 100;

   printf("\nExpanded memory:\n");

   for (x = 0; x < 10; x++)
      printf("number[%d] = %d\n", x, number[x]);


   free(number);
   return 0;
}

Result


Related Tutorials