Allocation
1
, Problem with Arrays
Sometimes
Amount of data cannot be predicted beforehand
Number of data items keeps changing during program execution
Example: Seach for an element in an array of N elements
One solution: find the maximum possible value of N and allocate
an array of N elements
Wasteful of memory space, as N may be much smaller in some
executions
Example: maximum value of N may be 10,000, but a particular
run may need to search only among 100 elements
Using array of size 10,000 always wastes memory in most
cases
2
, Better Solution
Dynamic memory allocation
Know how much memory is needed after the program
is run
Example: ask the user to enter from keyboard
Dynamically allocate only the amount of memory
needed
C provides functions to dynamically allocate
memory
malloc, calloc, realloc
3