#include "stdlib.h" int *ptr; ptr = (int *)malloc(sizeof(int));
Now, if the pointer returned by malloc() is not NULL, we can make use of it to access the memory indirectly. For example:
if (ptr != NULL) *ptr = 23;
Or, simply,
if (ptr) *ptr = 23; printf("Value stored is %d\n", *ptr);
Deallocate
free((void *) ptr);
or simply,
free(ptr);
It is possible to allocate a block of memory for several elements of the same type by giving the appropriate value as an argument. Suppose, we wish to allocate memory for 100 float numbers. Then, if fptr is a float *, the following statement does the job:
fptr = (float *) malloc(100 * sizeof(float));
No comments:
Post a Comment