/* CSE 333 Su12 Lecture 5 demo: arraycopy.c */ /* Gribble/Perkins */ /* Dynamic array allocation */ #include // Return a pointer to a new array with size elements initialized to // a copy of a[0..size-1]. Return NULL if allocation fails. int *copy(int a[], int size) { int i, *a2; a2 = malloc(size * sizeof(int)); if (a2 == NULL) { // out of memory return NULL; } // copy argument array to new array for (i = 0; i < size; i++) a2[i] = a[i]; return a2; } // Create copy of array and release storage after any processing int main(int argc, char **argv) { int nums[4] = {1,2,3,4}; int *ncopy = copy(nums, 4); // make sure copy succeeded by checking for NULL return if (ncopy == NULL) { // out of memory return -1; } // .. do something with the array here .. // when you're done, free up the memory free(ncopy); return 0; }