Tutorial exercises #8: Pointers
QUESTION 1
Write a function with the signature
int compare_strings(char *s1, char *s2)
that returns
-1 if s1 is smaller than s2,
0 if the two strings s1 and s2 are equal, and
1 if s1 is greater than s2.
s1 is smaller than s2 if, in the first position in which they differ,
the ASCII value of the character in s1 is smaller than the ASCII value
of the character in s2.
Write your code using pointers, *without* using array notation.
QUESTION 2
Write the code of the function with the following description and signature:
// This function swaps the two integers pointed-to by its two
// arguments.
void swap(int *p1, int *p2)
QUESTION 3
Write the code of the function with the following description and signature:
// This function returns a pointer to the smallest element of
// the array pointed to by the first argument, whose size is given by
// the second argument. array_size must be greater than zero.
const int *get_smallest(const int *array, int array_size)
QUESTION 4
Write the code of the function with the following description and signature:
// Sort the array pointed to by the first argument, whose size
// is given by the second argument.
void select_sort(int *array, int array_size)
It should use both of the functions from the previous questions.
QUESTION 5
Suppose you are a programmer working for Virgin Blue (one of Australia's
two main domestic airlines), and in one of your programs, you need a variable
that represents the number of occupied seats on a flight. When you define
this variable, which integer type do you use for it?
QUESTION 6
There are two popular ways to do a linear search of an array, in this case,
the array "a" in which the first "N" elements are meaningful.
The first approach is the simple, direct approach:
found = FALSE;
i = 0;
while (i < N) {
if (a[i] == key) {
found = TRUE;
break;
}
i++;
}
The second approach uses what is called a *sentinel*. It ensures that the
search finds the key it is searching for by putting it at the end of the array
before starting the search (this copy of the key is the sentinel), and then
after the search, it checks whether the found element was the sentinel or not:
i = 0;
a[N] = key;
while (a[i] != key) {
i++;
}
if (i < N) {
found = TRUE;
} else {
found = FALSE;
}
What are the respective advantages of these two approaches?