Using Pointers to Structures


Before we move on, take a look at some examples and we'll step through them so you can be sure you're learning all this. Here we go..

#include <iostream.h>

struct food {
   int rating;      /* Rating, out of ten */
   double weight;   /* Weight, in Pounds */
   int ttc;         /* Time To Cook */
   int calories;    /* Seconds it takes to cook */
};

void main(void)
{
   food good;   /* A can of Jolt Cola */
   food *bad;   /* A school "lunch"   */

   bad = new food;  /* Create the school "food" */

   good.rating = 10;  /* Fill in Jolt Cola's stats */
   good.weight = .2;
   good.ttc    = 0;
   good.calories = 150;

   bad->rating = 1; /* Fill in School "Food"'s stats */
   bad->weight = 5.0;
   bad->ttc    = 30;
   bad->calories = 1400;

   if (good.rating > bad->rating)
     cout << "I like Jolt Cola more than that icky pseudo-food." << endl;
   else
     cout << "I like watching my food glow!" << endl;

}

Here's the breakdown: First, a structure named food is defined, detailing a bunch of variables I'd use to describe a food. Don't forget that semicolon at the end of the structure's definition! Inside the main procedure, a variable good is defined of type food, and a variable bad is defined to be of type pointer-to-food. Right afterwards, bad is filled is given something to point at. Note that saying "bad = new food" is just like you've done in the past, nothing's changed. Next, the variables are all given values. Finally, a comparison of good.rating and bad->rating is done; if good.rating is higher (in this code, it is), it spits out a message saying so. If not, is spits out a message saying how much the program likes school lunch.

(Only a sick, sick person would change the rating of school food so that it was higher than Jolt Cola, but go ahead and try it for educational value)


Table of Contents

Structures | Pointing to Structures | Using Pointers to Structures | Using Escape Codes
Shortcuts | Exercises