Question: A. Design of an Array Library in C programming In the last assignment we solved the problem of computing the median of a set of

A. Design of an Array Library in C programming

In the last assignment we solved the problem of computing the median of a set of integers read from stdin. Since the size of the set was not known a priori, we used realloc to let the array where the numbers were stored grow as required. The solution was rather complicated for such a simple task. In this exercise, we design an array library that hides the details of resizing in the implementation. The user can blithely call the arrayPushBack function (part of the library API) to add an element to the array.

You have to write 4 functions in array.c: deleteArray, arrayPushBack, arrayPrint, and arraySort. For the last one, use qsort in your implementation. For arrayPushBack, you should make use of resizeArray (already in array.c).

#include #include #include "array.h"

struct _array { size_t capacity; /* elements allocated */ size_t inUse; /* elements currently in use */ void ** data; /* actual data */ };

array * newArray(void) { array * a; a = (array *) malloc(sizeof(array)); if (!a) return NULL; a->capacity = 1; /* parsimonious */ a->inUse = 0; a->data = (void **) malloc(sizeof(void *) * a->capacity); if (!a->data) { free(a); return NULL; } return a; }

void deleteArray(array * a) {

/* Your code goes here. */ }

int resizeArray(array * a, size_t newSize) { if (!a) return -1; if (newSize > a->capacity) { /* To avoid too many calls to realloc, we choose the larger of * twice the current size and the new requested size. */ size_t newCapacity = 2 * a->capacity; if (newCapacity < newSize) newCapacity = newSize; void ** tmp = (void **) realloc(a->data, newCapacity * sizeof(void *)); /* If the allocation fails, leave the array alone. */ if (!tmp) return -1; a->data = tmp; a->capacity = newCapacity; } /* Here we are guaranteed that newSize <= a->capacity. */ a->inUse = newSize; return 0; }

int arrayNum(array const * a, size_t * num) { if (!a || !num) return -1; *num = a->inUse; return 0; }

int arrayGet(array const * a, size_t index, void ** e) { if (!a || !e || index >= a->inUse) return -1; *e = a->data[index]; return 0; }

int arrayPushBack(array * a, void * e) { /* Your code goes here. Use resizeArray. */ }

int arrayPut(array * a, size_t index, void * e) { if (!a || index >= a->inUse) return -1; a->data[index] = e; return 0; }

int printArray(array const * a, printFn f) { /* Your code goes here. */ return 0; }

int sortArray(array * a, compareFn f) { /* Your code goes here. Use qsort. */ return 0; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!