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...
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...
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,...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any type dynamic arrays (replace string by the template in all instances below). • The class should have: – A private member variable called dynamicArray that references a dynamic array of type string. – A private member variable called size that holds the number of entries in the array. – A default constructor that sets the dynamic array to NULL and sets size to 0....
You are asked to implement a C++ class to model a sorted array of unsigned integers....
You are asked to implement a C++ class to model a sorted array of unsigned integers. The class is to be used in an embedded application that cannot assume the presence of the STL. The array has to be dynamically allocated in such a way that allows programmers using it to specify the required size. Your class should should: (1) provide the appropriate constructors and destructor; (2) provide methods for updating, and showing numbers in/to the array (e.g., to be...
Note: Do not use classes or any variables of type string to complete this assignment Write...
Note: Do not use classes or any variables of type string to complete this assignment Write a program that reads in a sequence of characters entered by the user and terminated by a period ('.'). Your program should allow the user to enter multiple lines of input by pressing the enter key at the end of each line. The program should print out a frequency table, sorted in decreasing order by number of occurences, listing each letter that ocurred along...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT