9.1 Structured Data
The C programming language provides a mechanism for creating new data types that can be used to create variables for storing structured or related data. For example, suppose we want to define a data type that can be used to store the data for a single card in a 52 card playing deck. Ideally, we want to store the suit as a character and the face value of the card as an integer. This can be accomplished by declaring or defining a structured type using the struct keyword:
- struct Card {
- char suit;
- int value;
- };

When defining a struct, you must include a semicolon after the closing brace. This is one of only a couple of places in C where a semicolon follows a brace.
This declaration defines a new data type, Card, that can be used for declaring variables to store data related to playing cards. Here, we declare a Card variable, ace
- struct Card ace;
which can be represented graphically as
The variable ace has two named parts, called fields, suit and value, which are similar to the data fields of objects in Python. In C, these fields are treated like any other variable, except they are stored within a container with a single name, ace.
|
Defining a Struct
struct new-type-name {
type field;
type field2;
:
};
The
struct keyword is used to define a new data type that can be used to create variables that can store structured or related data. Such variables are often known as records.
|
To access a field of a struct variable, we use the "dot notation"
var-name.field-name
similar to that used with the data fields of objects in Python. Suppose we want ace to store or represent the Ace of spades. We can initialize the fields as follows:
- ace.suit = 'S';
- ace.value = 1;
which results in
Within a given structure, the field names must be unique. Fields within different structures, however, can have the same name as used in another structure. Consider the following declarations:
- struct Point {
- int x;
- int y;
- };
- struct Point3D {
- int x;
- int y;
- int z;
- };
- struct Point p1;
- struct Point3D p2;
This does not cause confusion because a field must always be accessed through the struct variable
- printf("(%d, %d)", p1.x, p1.y);
- printf("(%d, %d, %d)", p2.x, p2.y, p2.z);
Thus, it is clear that we can access p1.x and p2.x without there being confusion as to which x field we are referring to.
Declare a struct variable twoClubs and set the field values to represent the two of clubs.
- struct Card twoClubs;
- twoClubs.suit = 'C';
- twoClubs.value = 2;

