/* File: malloc4.c malloc can fail! */ #include #include main() { int *ptr1 ; int i, size, r ; printf ("size of array = ? ") ; r = scanf("%d", &size) ; if (r < 1) { fprintf(stderr, "Need an integer! Bye!\n") ; exit(1) ; } /* Get memory for an array using malloc */ ptr1 = (int *) malloc(size*sizeof(int)) ; if (ptr1 == NULL) { fprintf(stderr, "malloc() failed!\n") ; exit(1) ; } /* Initialize array using array notation */ for (i = 0 ; i < size ; i++) { ptr1[i] = i*i ; } /* Print array contents */ printf("Array pointed by ptr1:\n") ; for(i = 0 ; i < size ; i++) { printf("%3d ", ptr1[i]) ; } printf("\n\n") ; }