C Books Guide and List
C++ Books Guide and List
Best Java Books

3,749 questions

4,049 answers

114 comments

10,705 users

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

0 votes
192 views
asked Jan 8, 2014 by keem Expert (13,240 points)

1 Answer

0 votes
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.
answered Jan 8, 2014 by rajesh Guru (39,140 points)

Related questions

0 votes
1 answer 205 views
0 votes
1 answer 47 views
0 votes
1 answer 39 views
39 views asked Jul 10, 2011 by denis Sr Member (2,740 points)
0 votes
1 answer 393 views
...