Prelab: Week of September 9th
You’ve created a general-purpose function for allocating an array
with elements of any data type:
array = createArray(numElems, elemSize);
Now we want to generalize the function so that the result secretly
stores the size (number of elements) with the array so that we can
implement the following function
size = getArraySize(array);
which allows the user to determine the number of elements in a
given array whenever its needed. You’ll want to declare the
parameter to be void* since it will need to work for any array of
any data type, and you’ll want to do the same for the other
function that will clearly be needed:
freeArray(array);
This is needed because free(array) won’t work correctly. Why?
As discussed in lecture, we can’t simply use free(array)because it
requires the address that was given to us by malloc. What is
returned from createArray is not that address. (Yes, it allocates
memory using malloc, but what else does it do?)
In summary, for the next prelab you’ll need to implement the
following three functions:
void * createArray(int n, int elemsize)
int getArraySize(void *array)
void freeArray(void *array)
One question you’ll have to answer for yourself is whether the user
will need to cast their array as (void *) when passing it
to getArraySize and freeArray. If so then that will have to be
documented in the comments of your implementations.
Another question you might consider is whether other information
could be usefully stored with arrays in a similar way.
It turns out the general version of the three functions can be
implemented almost as easily as the original versions specialized
for integers. HINT: Within your functions you can treat the chunk
of memory allocated for the user as an array of whatever data type
you choose, e.g., whatever would be most convenient for you.
#include<stdio.h>
#include<stdlib.h>
void* createArray(int numElems, int elemSize) {
int size = numElems*elemSize;
void* array = malloc(size + sizeof(int));
int* temp_array = (int*) array;
temp_array[0] = numElems;
array = (void*) ++temp_array;
return array;
}
int getArraySize(void* array) {
int* temp_array = (int*) array;
--temp_array;
return temp_array[0];
}
void freeArray(void* array) {
int* temp_array = (int*) array;
--temp_array;
array = (void*) temp_array;
free(array);
}
int main() {
int n = 8, m = 3;
void* ptr = createArray(n,m);
printf("%d", getArraySize(ptr));
freeArray(ptr);
}
Get Answers For Free
Most questions answered within 1 hours.