Example:
#include <stdlib.h> /* for malloc() */
#include <stdio.h>
int main(void) {
int *dynArrPtr;
dynArrPtr = (int *) malloc(50 * sizeof(int));
if (dynArryPtr == NULL) {
fprintf(stderr, "No memory!!\n");
exit(1)
}
/* do something with the array */
free (dynArrPtr);
return 0;
}
- sizeof(varType) returns the amount of memory space
required for one variable of type varType. The amount of
memory space is measured by a unit called bytes.
- malloc(size) will allocate the memory of size, and
return the address of this memory.
- You need to tell that the returned address is interpreted as a
pointer to a certain type (int * in this case). This is
called casting. You have encountered casting when you
were converting integer to double with (double).
- It is important to check whether malloc()
successfully find memory. If unsuccessful, the pointer become
something called NULL pointer. This means that the
pointer is NOT pointing to anywhere.
- After you are done using the memory, you need to tell that you
don't need the memory any more by free(ptr). If you keep
making new arrays without freeing the ones you don't need any
more, you might use up all memory. The memory will be released
when the program ends.