/* File: malloc3.c A common mistake using dynamically allocated arrays. */ #include #include #define TOP 17 main() { double *ptr1, *ptr2, *ptr3 ; int i ; /* Get memory for an array using malloc */ ptr1 = (double *) malloc(TOP*sizeof(double)) ; if (ptr1 == NULL) { fprintf(stderr, "malloc() failed!\n") ; exit(1) ; } /* Initialize array using array notation */ for (i = 0 ; i <= TOP ; i++) { /* BIG MISTAKE */ ptr1[i] = i*i ; } printf("Everything is fine up to now, or is it?\n") ; /* Get memory for an array using calloc */ printf("Calling calloc()...\n") ; ptr2 = (double *) calloc(TOP, sizeof(double)) ; printf("... return from calloc().\n") ; 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("%3.0f ", ptr1[i]) ; } printf("\n\n") ; printf("Array pointed by ptr2:\n") ; for(i = 0 ; i < TOP ; i++) { printf("%3.0f ", ptr2[i]) ; } printf("\n\n") ; }