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.
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;
my_stock.id my_stock.value my_stock.buying my_stock.buying.whole my_stock.selling.denomWe 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.denomThe 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;