[previous_group] * [up] [next] [next_group]

Structures

A sneak preview

We have seen the convenience of being able to group together all releated information into one data structure, giving it one name, can be. The compound data structure we have seen, an array, has the limitation that all of the data items must be the same type.

C provides a second compound data structure where we can group together data items of different types, and refer to them with a single name, called a structure.

How do we define a structure?

We define a structure by declaring a user defined type, listing all of the fields contained in the structure:
struct stock {
    char id[MAX_NAME];
    int shares;
    int whole;
    int numer;
    int denom;
    float value;
};

Here we are defining a new type called struct stock. It contains 6 fields; a character array, 4 integers, and a float. The names in those field declarations are the field names.

The fields in a structure can be any known type, including scalars, arrays, even other structures. In fact, it might be better to define:

struct price {
     int whole;
     int numer;
     int denom;
};

struct stock {
     char id[MAX_NAME];
     int shares;
     struct price buying;
     struct price selling;
     float value;
};

We can then declare a variable of type struct stock:
     struct stock my_stock;

How do we access the data in a structure?

The "dot" operator (.) is used to access a field:
     my_stock.id
     my_stock.value
     my_stock.buying
     my_stock.buying.whole
     my_stock.selling.denom
We can even declare an array of stock structures as the portfolio:
     struct stock folio[MAX_STOCKS];

and access individual stock data as:
     folio[i].id
     folio[i].value
     folio[i].buying
     folio[i].buying.whole
     folio[i].selling.denom
The other operator used to access structures (->), is used when we have a pointer to a structure:

   struct stock *this_stock;

        this_stock = folio+i;

        this_stock->shares = 57;
This has the same meaning as:
        (*this_stock).shares = 57;

[up] to Overview.

[next]