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:

    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)

    Girls who put out are tramps. Girls who don’t are ladies. This is, however, a rather archaic usage of the word. Should one of you boys happen upon a girl who doesn’t 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)