Using C programming language, please provide code for the function named _setCap
ID: 3706715 • Letter: U
Question
Using C programming language, please provide code for the function named _setCapacityDynArr.
# ifndef TYPE
# define TYPE int
# endif
struct DynArr
{
TYPE *data; /* pointer to the data array */
int size; /* Number of elements in the array */
int capacity; /* capacity of the array */
};
void initDynArr(struct DynArr *v, int capacity)
{
v->data = malloc(sizeof(TYPE) * capacity);
assert(v->data != 0);
v->size = 0;
v->capacity = capacity;
}
void freeDynArr(struct DynArr *v)
{
if(v->data != 0)
{
free(v->data); /* free the space on the heap */
v->data = 0; /* make it point to null */
}
v->size = 0;
v->capacity = 0;
}
int sizeDynArr( struct DynArr *v)
{
return v->size;
}
void addDynArr(struct DynArr *v, TYPE val)
{
/* Check to see if a resize is necessary */
if(v->size >= v->capacity)
_setCapacityDynArr(v, 2 * v->capacity);
v->data[v->size] = val;
v->size++;
}
The only thing missing now is the _setCapacityDynArr function. Complete the implementation of _setCapacityDynArr. Pay careful attention to the order of operations. Remember that since you’re creating a new array, you’ll want to eventually get rid of the old one to avoid a ‘memory leak’.
void _setCapacityDynArr(struct DynArr *v, int newCap)
{
}
Explanation / Answer
# ifndef TYPE
# define TYPE int
# endif
struct DynArr
{
TYPE *data; /* pointer to the data array */
int size; /* Number of elements in the array */
int capacity; /* capacity of the array */
};
void initDynArr(struct DynArr *v, int capacity)
{
v->data = malloc(sizeof(TYPE) * capacity);
assert(v->data != 0);
v->size = 0;
v->capacity = capacity;
}
void freeDynArr(struct DynArr *v)
{
if(v->data != 0)
{
free(v->data); /* free the space on the heap */
v->data = 0; /* make it point to null */
}
v->size = 0;
v->capacity = 0;
}
int sizeDynArr( struct DynArr *v)
{
return v->size;
}
void addDynArr(struct DynArr *v, TYPE val)
{
/* Check to see if a resize is necessary */
if(v->size >= v->capacity)
_setCapacityDynArr(v, 2 * v->capacity);
v->data[v->size] = val;
v->size++;
}
void _setCapacityDynArr(struct DynArr *v, int newCap)
{
struct DynArr *new_v = malloc(sizeof(TYPE) * newCap);
int i;
for(i = 0; i < newCap/2; ++i) {
new_v[i] = v[i];
}
free(v);
v = new_v;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.