1. [4 marks] (trick question)

a) How does the following function in C find the size of the array parameter?

void f(int *p)
{
    ...
}

Answer:

Well, certainly not with "sizeof p".

Maybe the size of the array parameter is defined as part of the interface, like how the pipe() kernel call requires a parameter which is a pointer to the zeroth item of an array of two elements.

Or maybe there is some other information available about the size of the item. Perhaps the size is stored in a global variable. Or it is possible for the data to indicate its own end in some way, as in part b:


b) Under what circumstances would the answer to part (a) be different if the parameter were of type "char *"?

Answer:

If it is considered to be a string, then there should be a zero byte in the array somewhere before the end of the array, and this indicates the end of the string. It still doesn't really tell you how big the array is, e.g. if f() needed to know how much further data it could strcat() onto the end of p without exceeding the array bounds then this wouldn't help.


(Grading note for question 1: Obviously you didn't have to write as much philosophy as above. The important points are: (a) you can't get the size of the array out of the pointer; and (b) C strings indicate their own end with the \0.)


[press 'back' in your web browser to return to where you were in the exam]