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:
“Girls who put out are tramps. Girls who dont are ladies. This is, however, a rather archaic usage of the word. Should one of you boys happen upon a girl who doesnt put out, do not jump to the conclusion that you have found a lady. What you have probably found is a lesbian.”
—Fran Lebowitz (b. 1951)
“Pythagoras, Locke, Socratesbut 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 (17881824)