/* CSE 303, Spring 2009, Marty Stepp This program uses heap memory allocation (malloc) to return a copy of an array. */ #include #include int* copy(int a[], int size); int main(void) { int i; int nums[4] = {7, 4, 3, 5}; int* nums2 = copy(nums, 4); // print the values from the copy array to make sure it worked for (i = 0; i < 4; i++) { printf("nums2[%d] is %d\n", i, nums2[i]); } // we should free all our malloc'd memory // (though in this case it doesn't matter much because the program is about // to exit anyway, at which point the memory would be reclaimed) free(nums2); nums2 = NULL; return 0; } /* Returns a new heap-allocated array that is a copy of the given array. */ int* copy(int a[], int size) { int i; int* a2 = malloc(size * sizeof(int)); for (i = 0; i < size; i++) { a2[i] = a[i]; } return a2; }