/* File: malloc2.c Simple memory allocation */ #include #include #define TOP 17 main() { int *ptr1, *ptr2, *ptr3 ; int i ; /* Get memory for an array using malloc */ ptr1 = (int *) malloc(TOP*sizeof(int)) ; if (ptr1 == NULL) { fprintf(stderr, "malloc() failed!\n") ; exit(1) ; } /* Initialize array using array notation */ for (i = 0 ; i < TOP ; i++) { ptr1[i] = i*i ; } /* Get memory for an array using calloc */ ptr2 = (int *) calloc(TOP, sizeof(int)) ; if (ptr2 == NULL) { fprintf(stderr, "calloc() failed!\n") ; exit(1) ; } /* Initialize array using pointer arithmetic */ ptr3 = ptr2 ; for (i = 0 ; i < TOP ; i++) { *(ptr3++) = i*i ; } /* Print array contents */ printf("Array pointed by ptr1:\n") ; for(i = 0 ; i < TOP ; i++) { printf("%3d ", ptr1[i]) ; } printf("\n\n") ; printf("Array pointed by ptr2:\n") ; for(i = 0 ; i < TOP ; i++) { printf("%3d ", ptr2[i]) ; } printf("\n\n") ; }