CS 246 Lab 6
Spring 2017
Write a suite of functions to implement a resizable array of int
s, along the lines of Java’s ArrayList
. Test your functions appropriately using check
.
Here are the function prototypes:
typedef struct array {
int* mem; // the memory
int size; // the size of the memory region
int num_elements; // the actual number of elements (<= size)
} array;
// create a new, empty array, with an initial size of 10 but no elements
array new_array();
// add a new element to the end of the array
void add_element(array* arr, int new_elt);
// access an element in the array. Returns -1 if the index is out of range.
int get(array* arr, int index);
// change an element in the array. Returns the old element if the index is
// in range, or -1 otherwise
int set(array* arr, int index, int new_val);
// remove an element from the array, shifting rightward elements to the left
void remove_element(array* arr, int index);
// returns the number of elements in an array
int num_elements(array* arr);
// release the memory used for this array (but not the array structure itself)
void free_array(array* arr);
// (a bit harder)
// adds an element at the given (non-negative) index, enlarging the array
// and shifting elements to the right to make it fit
void add_element_at(array* arr, int index, int new_elt);