2.7. Structures


Structure types

A structure is a collection of variables.

Define a structure type as in this example.

struct cell
{
  int          n;
  struct cell* next;
};
Notice the semicolon at the end. Also notice that the type is called struct cell, not just cell.


Creating structures

C allows you to create a structure either in a stack frame (as an automatic variable) or in the heap. (In Java, you can only create an object in the heap.)

Statement

struct cell c;
creates automatic variable c of type struct cell. Statement
struct cell* p = (struct cell*) malloc(sizeof(struct cell));
creates allocates one cell in the heap and stores the address of the allocated cell into automatic variable p.


Naming structure types

Type definition

  typedef struct cell 
  {
    int n;
    struct cell* next;
  }
  CELL;
defines type struct cell and makes CELL another name for it. Now you can write
  CELL* p = (CELL*) malloc(sizeof(CELL));


Selecting parts of a structure

To select a variable from a structure of type CELL, use a dot, as in Java. So if c has type CELL then

To select a variable from the structure pointed to by a given pointer, use -> instead of a dot. If p has type CELL* then


Defining constructors

Define a constructor as an ordinary function. Do not try to write it inside the structure type definition. For example,

  CELL* newCell(int m, CELL* q)
  {
    CELL* p = (CELL*) malloc(sizeof(CELL));
    p->n    = m;
    p->next = q;
    return p;
  }

defines constructor newCell. Notice that it actually returns a pointer to a CELL. See the next item.


Practical issues

A structure is similar to a Java class, but with heavy restrictions. There are only variables. There are no instance methods or static methods associated with a structure.

All of the variables are public. There are no static variables.

But, once you accept those restrictions, you can imagine a value of a structure type to be similar to a Java object.

Java stores all objects in the heap. Unless you are sure that an object is only needed during a call to the function that creates the object, you would do well to use the same principle. Allocate objects in the heap. Refer to them by pointers.


Example

See linkedlist.h and linkedlist.c for a vey small definition of linked lists.