C Dynamic Memory Allocation - Usage Example

Usage Example

The standard method of creating an array of 10 int objects:

int array;

However, if one wishes to allocate a similar array dynamically, the following code could be used:

/* Allocate space for an array with ten elements of type int. */ int *ptr = (int *) malloc(10 * sizeof(int)); if (NULL == ptr) { /* Memory could not be allocated. The program should handle the error here as appropriate. */ } else { /* Allocation succeeded. Do something with it... */ /* We are done with the array of ints, and can free the block of memory */ free(ptr); /* The pointed-to address must not be used again, unless re-assigned by another call to malloc. */ ptr = NULL; }

malloc returns a null pointer to indicate that no memory is available, or that some other error occurred which prevented memory being allocated.

Read more about this topic:  C Dynamic Memory Allocation

Famous quotes containing the word usage:

    Pythagoras, Locke, Socrates—but pages
    Might be filled up, as vainly as before,
    With the sad usage of all sorts of sages,
    Who in his life-time, each was deemed a bore!
    The loftiest minds outrun their tardy ages.
    George Gordon Noel Byron (1788–1824)

    ...Often the accurate answer to a usage question begins, “It depends.” And what it depends on most often is where you are, who you are, who your listeners or readers are, and what your purpose in speaking or writing is.
    Kenneth G. Wilson (b. 1923)