Fundamentals of Programming using C++


[Top] [Topic] [Task] [Test] [Feedback to Author] [TTT index]

Topic 17: Structures

What are structures?

In many data processing applications, individual pieces of data need to be grouped together to form a complete description of some item. For example, a library book is usually recorded by writing down its author, title, ISBN, publisher and date. When we group these five pieces of information together we define a complete record of the book.

Note that each individual piece of information (usually called "fields" or "members") might be of a different type. So, we can't group these fields together as elements in an array because all the elements of arrays must be of the same type.

Structure Definition

C++ provides the struct data type to hold a collection of fields together. The fields may be of different types. Here is a struct (structure) which could hold the fields needed for a item of stock in a grocery store.
  struct stock_item
  {	
    char item_code[5]; // one char for the null	
    char description[50];	
    int num_in_stock;	
    float price;
  }; // semicolon is required

Once a structure type like this has been defined, you can declare variables of that type like this:

  stock_item widgit; // creates one stock_item variable.

Now you can store all the information about one (only) item of stock. This is done like this:

  widgit.num_in_stock = 17;	
    // there are 17 of these items on the shelf

  widgit.price = 12.78;  // they cost $12.78 each

  strcpy( widgit.item_code, "MC36" );	
    // item_code is a STRING of 4 chars, so must use strcpy

  strcpy( widgit.description, "Motorcycle Gloves (Pair)" );

Note the use of the full stop between the name of the structure variable and the field or member which is being accessed. This is always the case, so, to access any particular field of a struct, we write:

  structvariablename.fieldname

Structure definitions in the program layout

Structure definitions are best thought of as the definition of a new type of data, in fact, they can be considered as user-defined-types. Because structures are types, they should be defined early in a C++ program so that all functions can use the new type. It is recommended that the structure definition be placed directly above the list of function prototypes used by the program, as shown here.

  // Top of source code

  #include <iostream.h>
  // other includes

  struct video
  {
    char title[40];
    float price;
    char rating;
  };

  // Function prototypes

  void main( void )
  {
    video v;
    v.price = 23.95;
    // other code
  }

  // Function definitions

More sample structures

To generalise the principles of designing structs, I present here a few more examples. With each one I've included a brief discussion. In many ways, C++ structs mimic database records so some of the discussion is focused that way.

Playing cards

In a program which simulates a card game, it would be useful to design a structure which defines a new type called playing_card. A playing card has a suit (Hearts, Diamonds etc) and a numerical value (from 1 to 13)...

  struct playing_card
  {
    char suit;
    int value;
  };

In the program we would create a card like this:

  playing_card topcard;  // topcard is a variable of type playing_card

and to make it the Ace of Diamonds, we could write:

  topcard.suit = 'D';
  topcard.value = 1;

Of course a program which deals with (excuse the pun) one card only is not going to be very useful - but we'll see how to fix that in the next topic.

Two dimensional coordinates

If your program had to manage points on a plane, each with an x-value and a y-value, you could design a struct like this:
  struct point
  {
    int x;
    int y;
  };

To create a new point variable, and to set its values to represent the position (2,13) on a plane, you would write the code:

  point A;
  A.x = 2;
  A.y = 13;

Further, if you have two points, you could calculate the distance between them with this function:

  float distance( point A, point B )
  {  // assumes <math.h> included
    int delta_x = A.x - B.x;
    int delta_y = A.y - B.y;
    return sqrt( pow(delta_x, 2 ) + pow( delta_y, 2 ) );
  }

Bank Accounts

In a program which simulates the operation of an automatic teller machine (ATM), each customer has an account, a personal identification number (PIN) and an account balance. So, each customer's data could be encapsulated in a single structure, as follows:
  struct customer
  {
    char pin[5]; // 4 chars and a null
    int acc_num;
    float balance;
  };

If a customer with account number 12345, has $1388.76 in their account and their PIN is "help", then their structure could be created like this:

  customer richie_rich;
  richie_rich.balance = 1388.76;
  richie_rich.acc_num = 12345;
  strcpy( richie_rich.pin, "help" ); // assumes <string.h>

Object-Oriented Programming

You will be aware that C++ has a strong claim in the Object-Oriented Programming world. This TTT system does not cover OOP yet (but it will soon cover it). The work on structs covered here is the launching pad for learning OOP in C++. If you add member functions to structs so that they can carry processes as well as data, then you can create software objects using it.

To follow

Although structs are powerful data structures, a single structure in a program is not very useful. The real power comes when you have a collection of structures held in some other data structure such as an array. This is the subject of topic 18 in the TTT system..
[Top] [Topic] [Task] [Test] [Feedback to Author] [TTT index]

Topic 17: Structures.

  1. Using the playing card example from above, write a function which prints on the screen the full description of a given card. For example, if the card has its suit set as 'D' and its value set at 1 (as per the example), then your function will print:

      Ace of Diamonds
    

    Of course, your function should work for all playing cards which could be found in a normal deck.

    Sample Solution

  2. Design a struct which is suitable for holding a single compact disc (of the music variety). The structure should include at least the following members:

    Write a program which allows the user to enter the details of (only) three CDs and prints a tabular report showing the details.

    Sample Solution

  3. Design a structure which represents a circle. Its members will be a point (as defined in the example above) and a radius (a floating point number)

    Write a boolean function which returns TRUE (1) if a given point is inside a given circle or FALSE (0) if the point is outside the circle.

    Sample Solution


[Top] [Topic] [Task] [Test] [Feedback to Author] [TTT index]

Topic 17: Structures.

Click here to try this topic's test


[Top] [Topic] [Task] [Test] [Feedback to Author] [TTT index]

Feedback

I am interested in hearing your views about the TTT System or any of its content. If you would like to offer any comments or suggestions please email me:
Author:
Errol Chopping echopping@csu.edu.au
Lecturer in Computing
Charles Sturt University - Mitchell
Bathurst NSW 2795
Australia.
Last Update: Mar 18, 1996