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:
“I am using it [the word perceive] here in such a way that to say of an object that it is perceived does not entail saying that it exists in any sense at all. And this is a perfectly correct and familiar usage of the word.”
—A.J. (Alfred Jules)
“...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)