April 1999
CA208: 'C' PROGRAMMING

QUESTION 5

Total Marks: 20 Marks

Click here to access other questions

GRADE A
Sample student's solutions are indicated in green.
Return to Question 5

 

(a) Describe the effect of adding the keyboard static to a local variable in a procedure or function. [2]
The effect of keyword static, is that the local variable retains its value between function calls, and exists for the lifetime of program execution.

 

(b) Identify the difference between stack and heap allocated data in C. [3]
  • stack allocated data is allocated by the computer, when a procedure is entered, and so the contents (register) etc are saved onto a stack.
  • Heap allocated data is present only during the execution of the procedure.
  • Heap allocated data exists throughout the execution of program until the user frees the allocation by using 'free'.

 

(c) (i) Using a single statement, declare a one-dimensional integer array called digits, and initialise it with the values 10, 20, and 30. [2]
int digits[ ] = {10,20,30};

 

(ii) Using a single statement, declare a two-dimensional integer array of three elements by three elements, called moredigits, and initialise it with the following integer matrix:

(9, 8, 7)(6, 5, 4)(3, 2, 1)

[3]
int moredigits [3][3] = { 9,8,7,6,5,4,3,2,1};

 

(iii) Using a single statement, declare a character array called footy, and initialise it with the letters (c, f, e, e, d, n, u, d). The array should be no larger than is necessary to contain these letters. [2]
char footy[8] = {'c', 'f', 'e', 'e', 'd', 'n', 'u', 'd'};

 

(d) The following function is intended to return an array containing the numbers [4, 3, 2, 1]. Explain why the function may not work as intended.

int * fournums() {
   int res[] = {4, 3, 2, 1};
   return res;
}

[2]
  • The array res is allocated on the stack as it is a local variable of the procedure fournums.
  • Therefore the address of the string returned by the function will no longer be in scope, and will reference an invalid piece of memory when the function exits.

 

(e) Assume the following definition of the function foobar:

int foobar(int xs[], int n) {
   int i;
   for(i=0; (i<n) && (xs[i] < 0); i++) {}
   return ((i>=n)?(-1):i);
}

 

(i) Describe the result of evaluating foobar(xs, 6) when xs is the array

xs[] = {-20, 11, 1, 9, -6, 5}

[1]
1 is returned.
(ii) Describe the result of evaluating foobar(xs, 6) when xs is the array

xs[] = {0, 11, 0, -5, 6, 1}

[1]
0 is returned.

 

(iii) Describe the result of evaluating foobar(xs, 6) when xs is the array

xs[] = {20, 11, 1, 5, 6, 1}

[1]
0 is returned.

 

(iv) Describe the effect of foobar(xs, n) when given an arbitrary array xs containing n values. [3]
The function foobar determines the first positive integer of the array xs, and returns -1 if all the n elements of the array xs are negative, else it returns the subscript of the array the element (first positive) refers to.