CECS Home | ANU Home | Search ANU
The Australian National University
ANU College of Engineering and Computer Science
School of Computer Science
Printer Friendly Version of this Document

UniSAFE

Introduction to Computer Systems

Tutorial/Laboratory 03 - C I/O, Pointers and Structures

Week 4

As well as the preparation exercises required for this session, you should read through the tutorial exercises beforehand, and revise any relevant lecture notes and/or sections of your text book before your session (this in fact applies to all sessions).

Preparation Exercises [1 mark]

Complete the following questions on a separate sheet of paper, with your name and student number clearly written. Please ensure your writing is legible. Hand in to your tutor at the beginning of your tutorial / laboratory session. The following questions should serve as revision for you C programming from the previous session.

  1. Write a statement that declares an integer x and initializes it to 0.
  2. Write a statement to assign the integer variable x that value of the integer variable y plus 1.
  3. Write a statement to print out the value of the integer variable x.
  4. Write a statement to scan the read an integer value from standard input into the integer variable x.
  5. Write a for loop which prints out the values 1 to 10 on separate lines.
  6. Write a while loop which does the same as the above.
  7. Write a if-else statement which assigns the integer variable y to the absolute value of x.
  8. Write a statement to declare in integer array a which holds 4 elements.
  9. Write a for loop to set the ith element in the array a above to have the value two times i.
  10. Write a function which takes a single string parameter and prints it out.

Tutorial Questions [2 marks]

Work through the following questions in your session. Finish any uncompleted exercises for homework.

  1. Consider the declaration int a[8], b[4], *c;. How many bytes of memory would be allocated by this declaration on a 32-bit machine? Draw a diagram to illustrate this. Would the assignment statement b = a; be legal, and if so describe what effect it would have. How about c = a;?

  2. Pointers: true or false? (and why?)

    1. A variable in a C program, regardless of its type, must have an address.

    2. A variable of any type can be used to store the address of a variable.

    3. The address of a variable is expressed in hexadecimal form; therefore, only an integer type variable can be used to store the address of a variable.

    4. A pointer variable of any type can be used to store the address of a double variable.

    5. The indirection operator * may appear only on the left side of an assignment statement.

    6. The indirection operator * may appear on both sides of an assignment statement.

    7. The address of operator & may appear only on the left side of an assignment statement.

    8. The address of operator & may appear on both sides of an assignment statement.

    9. For an int variable aa, its address &aa is a constant, not a variable.

    10. Given char aa, *bb; and sizeof(aa) is 1 byte, then sizeof(bb) is also 1 byte.

  3. Consider the following code:

    #include <stdio.h>
    int main(void) {
    
      char str[80];
      char *p;
      int i;
    
      printf("Enter a string:\n");
      scanf("%80s", str);
      p = str;
    
      while(*p) *p++ -= 32;
      printf("%s\n", str);
    
      return 0;
    }
    

    Rewrite it (on paper) using array notation instead of pointers, i.e. the str[i] notation. Now state what the program does.

  4. In the following code:
    #include <stdio.h>
    void funct(int *p);
      
    int main(void) {
      int a[] = {4, 8, 10, 7, 9, -6, 3, 0, 7, 22, 1};
    
      funct(a+1);
      funct(a+2);
      funct(a+8);
      
      return 0;
    }
    
    void funct(int *p) {
      int x = 0, y = 0;
      int *pstart, *pend;
      pstart = p;
    
      while (*p >= 0) {
        x += *p++;
        y++;
      }
      
      pend = p;
      printf("y=%d x=%d pend-pstart=%d\n", y, x, pend-pstart);
    }
    
    1. What kind of argument is passed to funct()?
    2. What kind of information is returned by funct()?
    3. What information is actually passed to funct()?
    4. What is the purpose of the while loop that appears within funct()?
    5. What values are displayed by the printf() statement within funct()?

Laboratory Exercises[2 marks]

Execute the command cp -pr /dept/dcs/comp2300/public/lab3 . to copy over this lab's C program in your directory.

  1. Do tests numbered 10 and 11 (pointers Qs 1-5, and pointers and structures, Qs 1-5) from the Interactive Tests.

  2. The programs string.c and funct.c are from Tutorial Questions 3 and 4 respectively. Compile and run these programs, to verify your answers to those questions.

  3. The program readchars.c aims to read in from the keyboard two lines that contain two characters on each line. Inspect its code.

    It should produce the following, where AB and CD are the lines typed at the keyboard:

      Enter two characters (without spaces), then press return:
      AB
    
      First Character A Second Character B 
      Enter two MORE characters (without spaces), then press return:
      CD
    
      Third Character C Fourth Character D
    

    However the code does not print this for the third and fourth characters. Why is this? Fix the program so it works correctly.

  4. Write a program readstring.c that inputs a character string. The program should define the input character string as all entered characters from the first non-white space character to the next white space character. If the character string contains more than 20 characters, it should be truncated to contain just the first 20 entered characters. The program then prints out the string (with a "%s\n" format) and terminates. Note that the program prints nothing else.

    Example input/output line pairs:

    MYCHARACTERSTRING PLUS SOME OTHER DATA
    MYCHARACTERSTRING
    
    
      ANOTHER AND SOMETHING ELSE
    ANOTHER
    
    A_VERY_LONG_STRING_THAT_IS_TRUNCATED_AT_20_CHARACTERS
    A_VERY_LONG_STRING_T
    

    Note: a non-trivial extension to this exercise is to perform the same thing on multiple lines of input.

  5. The program struct.c defines a structure and initialises it. Add two printf() calls to print the components of me firstly using me and then using pme.

  6. Some of the C library functions and many Unix system library functions return pointers to structures. An example of this is the Unix gettimeofday() function (do man gettimeofday to read all about it). This function has the following prototype, that is also defined in the header file <sys/time.h>:

      int gettimeofday(struct timeval *tv, struct timezone *tz);
    

    The program timeloop.c uses gettimeofday() to measure the elapsed time required to execute a small loop. It will print a system error message if the call to gettimeofday() fails.

    Inspect the code of the program, then compile it and and try running it, supplying a largish value for the 1st parameter, e.g. ./timeloop 9000000. You will probably find the time taken is substantially less than one second. From the man page you will see that the second component of the timeval structure also contains the number of microseconds.

    Before the final printf() statement, compute the precise time (accurate to microseconds) that the loop took to execute as a floating point value, and assign it to loopTime. Now the program should print this time to 4 decimal places. Note: do not alter any of the printf() statements, nor add any others.

Once you are satisfied with the exercises, check your programs' correctness using the command:

previewAutoMark lab3 readstring.c timeloop.c

When all is working correctly show your solution to your tutor to get it marked.

  • Supplementary question: Return to program2.c of Laboratory 02 and add a function load_rainfall which has the file name as an additional input argument to month_rain[]. This function should read the data directly from the text file instead of getting in via standard input <. Use the functions fopen(), fscanf() and fclose() as discussed in the lectures.