Consider the following structure definition:
struct Card {
string face;
string suit;
};
Keyword struct
introduces the definition for structure Card
. The identifier Card
is the structure name
and is used in C++ to declare variables of the structure type
(in C, the type name of the preceding structure is struct Card
). Card
’s definition contains two string
members—face
and suit
.
The following declarations
Card oneCard;
Card deck[52];
Card* cardPtr;
declare oneCard
to be a structure variable of type Card, deck
to be an array with 52 elements of type Card
and cardPtr
to be a pointer to a Card
structure. Variables of a given structure type can also be declared by placing a comma-separated list of the variable names between the closing brace of the structure definition and the semicolon that ends the structure definition. For example, the preceding declarations could have been incorporated into the Card
structure definition as follows:
struct Card {
string face;
string suit;
} oneCard, deck[52], * cardPtr;
As with classes, structure members are not necessarily stored in consecutive bytes of memory. Sometimes there are “holes” in a structure, because some computers store specific data types only on certain memory boundaries for performance reasons, such as half-word, word or double-word boundaries. A word is a standard memory unit used to store data in a computer—usually two, four or eight bytes and typically eight bytes on today’s popular 64-bit systems. Consider the following structure definition in which structure objects sample1
and sample2
of type Example
are declared:
struct Example {
char c;
int i;
} sample1, sample2;
A computer with two-byte words might require that each of the members of Example
be aligned on a word boundary (i.e., at the beginning of a word—this is machine dependent). Figure 22.1 shows a sample storage alignment for an object of type Example
that’s been assigned the character 'a'
and the integer 97
(the bit representations of the values are shown). If the members are stored beginning at word boundaries, there is a one-byte hole (byte 1
in the figure) in the storage for objects of type Example
. The value in the one-byte hole is undefined. If the values in sample1
and sample2
are in fact equal, the structure objects might not be equal, because the undefined one-byte holes are not likely to contain identical values.
Because the size of data items of a particular type is machine dependent, and because storage alignment considerations are machine dependent, so too is the representation of a structure.
Comparing variables of structure types is a compilation error.