Computer Systems Org I - Prof. Grishman

Lecture 20 - Nov. 10, 2005

Structures (P&P Chap. 19)

Structures in C provided the capability of grouping together several variables, called the members of the structure.  They are similar to a Java class with its fields, but there is no language-defined association of functions with structures the way there is of Java classes and their methds.

A structure consisting of two floating point members, x and y, is defined by
struct point {float x; float y;};
and then variables of this type can be declared
struct point p1;
As a slight shorthand,
typedef struct point Pair;
allows us to write 'Pair p1;' instead of 'struct point p1;'.

We can create a simple program with a function which acts as a constructor for Pairs (makepoint), a function which prints a Pair (printpoint), and a function which modified a Pair (movepoint).  Structures in C are normally passed by value, which is fine for printpoint, but for movepoint (in order to be able to modify the structure) we must explicitly pass the address.

#include <stdio.h>

struct point {float x; float y;};
typedef struct point Pair;

void printpoint (Pair);
Pair makepoint (float, float);
void movepoint (Pair*);

main() {
        /* struct point p1; */
        Pair p1;
        Pair p2;
        p1 = makepoint (3., 4.);
        movepoint (&p1);
        printpoint (p1);

/*  makepoint constructs a Pair */

Pair makepoint (float x, float y) {
        Pair temp;
        temp.x = x;
        temp.y = y;
        return temp;

/* printpoint prints a Pair */

void printpoint (Pair z) {
        printf ("Pair is (%f, %f)\n", z.x, z.y);

/*  movepoint increments both coordinates by 1. */
/*  its argument is a pointer to a Pair         */

void movepoint (Pair* z) {
/*  we want to
      1. dereference (get the Pair)
      2. get component x
      3. autoincrement that component
      (and then do the same for y)
    we can do that with the following expressions (note the parentheses!)
    or with the following, equivalent, C notation */