next up previous contents index
Next: Enumerated types Up: Types Previous: Dynamic memory   Contents   Index


Structures

C has a notion similar to Pascal's record, called the struct, which allows you to keep various related pieces of information together, without having to declare lots of variables:

  
{ 
  /*  define the type `struct point' as convenient way of describing
      points in two-dimensions.  This definition can occur at any place
      that a variable declaration would be legal */
  struct point {
    double x;  
    double y;
  };             
 
  struct point pt;   /*  declare pt as a `struct point'  */

  /*  we want to make pt represent (0,1)  */
  pt.x = 0.0;   /*  . gives access to the fields of a struct  */
  pt.y = 1.0;   
}
A quicker way of initializing a structure resembles that for arrays:

  
struct point the_origin = { 0.0, 0.0 };
The type of pt is struct point, and like any type of known size (the size is known because the compiler knows the size of a double), you can declare arrays of them:

  
struct  point {
  double x;  
  double y;
};               

struct point box[4];

box[0] = { 0.0, 0.0 };
box[1] = { 1.0, 0.0 };
box[2] = { 1.0, 1.1 };
box[3] = { 0.0, 1.0 };

To use a struct in more than one part of a program, the definition must occur above the point where it is first used.

  
struct point {
  double x;  
  double y;
};               

void display(struct point e) {
 
  printf("x = %f", e.x);
  printf("y = %f", e.y);
}
/* .. */
It is very common to pass pointers-to-structs rather than the structs themselves as arguments to a function. If x is a pointer-to-struct, C has a nice syntax for indirecting the pointer followed by selecting one of the fields, ->. The function display would more normally be written as

  
/* .. */

/*  take a pointer-to-struct-point  */
void display(struct point* e) {
 
  printf("x = %f", e->x);     /*  e->x means (*e).x  */
  printf("y = %f", e->y);
}

int main(void) {
  /* .. */
  display(&box[0]);
}
structs support assignment from variables of the same type, but do not support comparison operators, not even tests for equality/non-equality.


next up previous contents index
Next: Enumerated types Up: Types Previous: Dynamic memory   Contents   Index
CATAM admin 2010-02-23