1. Engineering
  2. Computer Science
  3. code must be in c programming isnt just about writing...

Question: code must be in c programming isnt just about writing...

Question details

Code must be in C

Programming isn’t just about writing a program for one-time use to solve some problem. Large pieces of software (e.g., Photoshop) are constructed by creating special-purpose functions that can be used as building blocks to create even more powerful functions.

A programming language like C provides the bare minimum set of functions, e.g., input/output (I/O) functions like scanf and printf along with standard math and string functions. It doesn’t need to provide much more than that because the real power of a general - purpose programming language is that it allows the user to expand the language by creating libraries of new functions.

As I described in lecture, it’s possible to create a set of functions to improve the way arrays can be used in C. Specifically, we can create a function:

array = createIntArray(n);

which allocates an integer array of size n in a way that stores the size with the array so that it can be accessed when needed. This means that an array allocated in this way can be passed to functions without having to use a separate parameter to tell the function the size of the array. This is possible because we can also create a function:

size = getArraySize(array);

which provides the size of an array when needed. Of course, we'll also need a function to free the array: freeArray(array); 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 createIntArray is not that address. (Yes, the function createIntArray(n) allocates memory using malloc, but what else does it do?)

For this prelab, you will implement a generalization to work with any data type. How can this be done? Well, we’ll just need to pass the size of the data type. For example, if we want to allocate an array of n doubles we would call the createArray function as:

array = createArray(n, sizeof(double));

This can be done because the function doesn't ’t really need to know the data type, it just needs to know its size. As I mentioned in lecture, malloc does ’t actually know the data type of anything it allocates –it just receives an integer giving the size of the chunk of memory the user wants. 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 function, 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.

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution