Question

Prelab: Week of September 9th You’ve created a general-purpose function for allocating an array with elements...

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.

Homework Answers

Answer #1

#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);
}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
/************************************************************************************* Function Prototypes *************************************************************************************/ int ScanArray(char *fname, int myArray[], int nSize); void Ge
/************************************************************************************* Function Prototypes *************************************************************************************/ int ScanArray(char *fname, int myArray[], int nSize); void GenerateFromArray(void); /************************************************************************************/ /************************************************************************************/ int main(void) { /* This is the main() program. It should call the functions ScanArray() and GenerateFromArray() */ GenerateFromArray(); system("pause"); return 0; } /*************************************************************************************** Define this function to scan the elements of an array from the given data file "ArrayInp.dat". If the input file is not found, or contains invalid data, the function should return a 0 and print an error message. If the input...
IN C PROGRAMMING A Tv_show structure keeps track of a tv show’s name and the channels...
IN C PROGRAMMING A Tv_show structure keeps track of a tv show’s name and the channels (integer values) that broadcast the show. For this problem you can ONLY use the following string library functions: strcpy, strlen, strcmp. You MAY not use memcpy, memset, memmove. You can assume memory allocations are successful (you do not need to check values returned by malloc nor calloc). typedef struct tv_show { char *name; int num_channels, *channels; } Tv_show; a. Implement the init_tv_show function that...
How to use C++ figure this question? Collection and Sorted Collection An array is great for...
How to use C++ figure this question? Collection and Sorted Collection An array is great for storing a list of values. However, one challenge when working with arrays is they have a fixed size. If you declare an array of size 10 and later need to actually store 11 elements you have to create a new array and copy everything over. C++ (and other langauges) create classes that handle this and other operations behind the scenes. In this assignment, we...
Complete this in C++ and explain what is being done. 1      Introduction The functions in the...
Complete this in C++ and explain what is being done. 1      Introduction The functions in the following subsections can all go in one big file called pointerpractice.cpp. 1.1     Basics Write a function, int square 1(int∗ p), that takes a pointer to an int and returns the square of the int that it points to. Write a function, void square 2(int∗ p), that takes a pointer to an int and replaces that int (the one pointed to by p) with its...
One way to represent a very large integer (one that won't fit into a variable of...
One way to represent a very large integer (one that won't fit into a variable of type short, int, or even long) is to use an array. The array is of type int, so each element in the array can hold an integer -- we will store just one digit of our number per array element. So if a user entered 2375, it might be stored as -------------------------- | 2 | 3 | 7 | 5 | ... | --------------------------...
IntNode class I am providing the IntNode class you are required to use. Place this class...
IntNode class I am providing the IntNode class you are required to use. Place this class definition within the IntList.h file exactly as is. Make sure you place it above the definition of your IntList class. Notice that you will not code an implementation file for the IntNode class. The IntNode constructor has been defined inline (within the class declaration). Do not write any other functions for the IntNode class. Use as is. struct IntNode { int data; IntNode *next;...
ALL CODE MUST BE IN C++ Before you begin, you must write yourself a LinkedList class...
ALL CODE MUST BE IN C++ Before you begin, you must write yourself a LinkedList class and a Node class (please name your classes exactly ​as I did here). Please follow the below specifications for the two classes. Node.cpp ● This must be a generic class. ● Should contain a generic member variable that holds the nodes value. ● Should contain a next and prev Node* as denoted here. ● All member variables should be private. ● Use public and...
DIRECTIONS: IMPLEMENT QuickSort and MergeSort. You have been provided: 1. Functions to perform Merge (for MergeSort)...
DIRECTIONS: IMPLEMENT QuickSort and MergeSort. You have been provided: 1. Functions to perform Merge (for MergeSort) and Partition (for QuickSort). 2. In class we discussed the body of the recursive functions, the "brakes" needed to stop the recursion. You are expected to develop 2 RECURSIVE programs: 1. Complete the bodies of the sort functions, MergeSort and QuickSort. 2. Complate the main that tests each function. - program should not read inputs - stock the program with multiple arrays (test cases)...
There are two ways to write loops: (1) iterative, like the for-loops we're used to using,...
There are two ways to write loops: (1) iterative, like the for-loops we're used to using, and (2) recursive. Your prerequisite preparation for this course should have exposed you to both, although your working knowledge of recursive loops may not be as strong as that of iterative loops. Consider the following iterative function that prints an array of characters backward: #include <iostream> #include <cstring> // print an array backwards, where 'first' is the first index // of the array, and...
Consider the C program (twoupdate) to demonstrate race condition. In this assignment, we will implement Peterson's...
Consider the C program (twoupdate) to demonstrate race condition. In this assignment, we will implement Peterson's algorithm to ensure mutual exclusion in the respective critical sections of the two processes, and thereby eliminate the race condition. In order to implement Peterson's Algorithm, the two processes should share a boolean array calledflagwith two components and an integer variable called turn, all initialized suitably. We will create and access these shared variables using UNIX system calls relating to shared memory – shmget,...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT