Monday, 20 February 2012

How to use realloc() to dynamically increase size of an already allocated array? | C Programming

realloc(): This function is used to increase or decrease the size of any dynamic memory which is allocated using malloc() or calloc() functions.
Syntax: void *realloc(void *ptr, size_t newsize);
The first argument 'ptr' is a pointer to the memory previously allocated by the malloc or calloc functions. The second argument 'newsize' is the size in bytes, of a new memory region to be allocated by realloc. This value can be larger or smaller than the previously allocated memory. The realloc function adjusts the old memory region if newsize is smaller than the size of old memory.
If the newsize is larger than the existing memory size, it increases the size by copying the contents of old memory region to new memory region. The function then deallocates the old memory region. realloc function is helpful in managing a dynamic array whose size may change during execution.
Example: a program that reads input from standard input may not know the size of data in advance. In this case, dynamically allocated array can be used so that it is possible allocate the exact amount of memory using realloc function.