malloc
The malloc function dynamically allocates memory from the application memory heap. The function returns an address to the allocated memory block, which can be stored in a pointer to the desired data type.
The return value of the function is "void *", an it requires a cast to a pointer of the required data type.
The malloc function requires only one argument. The argument specifies the size of the memory block that the application is trying to allocate.
The following code shows an example of malloc in use:
#include <stdlib.h> #include <stdio.h> int main() { int i; int num_elements = 10; int *p; p = (int *)malloc(sizeof(int)*10); for (i=0; i<num_elements; i++) { p[i] = i; } for (i=0; i<num_elements; i++) { printf("the value is %d\n", p[i]); } return 0; }
Article created on 2008-08-19 22:00:41
Post a comment