Lesson 5: Structures
A C compiler.
Instructions on using the LCCWin32 Compiler.
Structures and their uses.
What is a
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:
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:
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?
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;
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:
Remember, the array starts from zero! And if we wanted to set the health of Player 8 to zero:
players.health = 0;
Thats all for now. The sixth Lesson will deal with Structures and a new concept called Linked Lists.
Copyright © 1997,
John Crickett & Neil Henderson.