/* Revised example from http://www.ihypress.net/programming/c/prog.php?chap=07&pgm=09 A dynamically-allocated 1-D array using "calloc" function Reallocating memory, if needed. */ #include #include int main (void) { double* array; /* declare a pointer only */ int i, size; /* ask user for size of array */ printf ("How large do you want your array? "); scanf ("%d", &size); /* allocate the array in the heap */ array = (double *) calloc (size, sizeof(double)); /* printing the array for verification -- surprise! a dynamic array is automatically initialized with zeros! */ for (i = 0; i < size; ++i) printf ("%6.2lf", array[i]); printf("\n"); /* Example of how to increase the memory allocated for array */ size = 2 * size; /* void *realloc( void *ptr, size_t new_size ); Reallocates the given area of memory. It must be previously allocated by malloc(), calloc() or realloc() and not yet freed with a call to free or realloc. Otherwise, the results are undefined. The reallocation is done by either: a) expanding or contracting the existing area pointed to by ptr, if possible. The contents of the area remain unchanged up to the lesser of the new and old sizes. If the area is expanded, the contents of the new part of the array are undefined. b) allocating a new memory block of size new_size bytes, copying memory area with size equal the lesser of the new and the old sizes, and freeing the old block. If there is not enough memory, the old memory block is not freed and null pointer is returned. */ array = (double *) realloc (array, size); /* printing the array for verification */ for (i = 0; i < size; ++i) printf ("%6.2lf", array[i]); printf("\n"); /* freeing the memory allocation */ free (array); return (0); }