//This program gives an example of how you can allocate memory //for an array and then read in the array and print it out in //reverse order. //Sasha Vassar Week 7 Lecture 11 #include //malloc() and free() live inside the #include void read_array(int *numbers, int size); void reverse_array(int *numbers, int size); int main (void) { int size; printf("How many numbers would you like to scan: "); scanf("%d", &size); //TODO: Allocate some memory space for my array and return a pointer //to the first element //Malloc is the function that allocates memory // Malloc returns a pointer to the allocated memory // Malloc takes in the number of bytes needed int *numbers = malloc(size * sizeof(int)); // 5 numbers = 5 * 4 = 20 bytes // A pointer can point to NULL, which means it is poitning to nothing! // if there is not enough memory that malloc needs, it will return a NULL //TODO: Check if there is actually enough space to allocate //memory, exit the program if there is not enough memory //to allocate. if (numbers == NULL) { printf("Error, malloc failed, there is not enough space to allocate\n"); return 1; } //Perform some functions here read_array(numbers, size); reverse_array(numbers, size); //Free the allocated memory //In this case, it would happen on program exit anyway free(numbers); return 0; } //Helper function that reads in numbers and places them into an array //Inputs are the pointer to the first element of the array, and the size of //the array. void read_array(int *numbers, int size){ int i = 0; while (i < size) { printf("Enter a number to scan in: "); scanf("%d", &numbers[i]); i++; } } //TODO: Finish the helper function to reverse the elements of the array void reverse_array(int *numbers, int size){ printf("Numbers reversed are:\n"); int last = size - 1; while (last >= 0) { printf("%d\n", numbers[last]); last--; } }