C Tutorial

Back to Tutorials

Next Lesson

 

Lesson 5: Structures

Lesson Requirements
A C compiler.

Instructions on using the LCCWin32 Compiler.

Lesson Summary
Structures and their uses.

What is a Structure?
Sometimes we want to store more data about an object than we can use by a basic type (i.e. an int, char, etc). Or we might wish to group together a set of attributes for an object. For example, in Quake we might wish to store information on the player(s) in a game. Each player would have the following attributes: Name, Health, Location, and so on.

We could store this information in a set of variables:

player_name
player_health
player_location

However, let's say we have a second player. We would have to create a copy of these variables, slightly renamed, for the second player:

player2_name
player2_health
player2_location

And what if there are ten players? We would need thirty variables to hold all of the attributes for these ten players. There are obvious reasons why this is not the best solution, and also some other reasons that we will go into later.

A better solution would be to have an array of a new data type, or structure, called "player". This is where structures become useful. A structure allows us to declare a new data type called "player" which has members (the attributes for the player): name, health, and location. So what does the code look like?

struct player
{
  char name[40];
  int health;
  int location;
};

NOTE: The location would actually be a Vector, but in this example we will keep things simple.

We could now declare a variable for player_one using this new structure, "player", as:

struct player player_one;

or even better, an array of players as:

struct player players[16];

Accessing the Members of a Structure
We need a way of accessing the members, or attributes, of the structure. We do this by using the "." (period) operator. For example, if we wanted to access the name of the player in the fourth array position:

players[3].name;

Remember, the array starts from zero! And if we wanted to set the health of Player 8 to zero:

players[7].health = 0;

Thats all for now. The sixth Lesson will deal with Structures and a new concept called Linked Lists.

 

Back to Tutorials

Next Lesson

 


Copyright 1997, John Crickett & Neil Henderson.
Legal Information