C examples for Memory:malloc
Memory acquired by malloc() can be treated much like array members.
These memory segments can be referenced with indexes.
#include <stdio.h> #include <stdlib.h> int main()/*from w ww . java2 s . c o m*/ { int *numbers; int x; numbers = (int *)malloc(5 * sizeof(int)); if (numbers == NULL) return 1; // return if malloc is not successful numbers[0] = 1; numbers[1] = 2; numbers[2] = 3; numbers[3] = 4; numbers[4] = 5; printf("\nIndividual memory segments initialized to:\n"); for (x = 0; x < 5; x++) printf("numbers[%d] = %d\n", x, numbers[x]); return 0; }