Structures
- Structures
- Structures are collections of variables grouped together under a common name. The variables within a structure are referred to as the structure’s members and may be accessed individually as needed.
Structures:
- May contain any number of members
- Members may be of any data type
- Allow a group of related variables to be treated as a single unit, even if different types
- Ease the organization of complicated data
Creating a Structure Definition
Syntax
struct structName
{
type1 memberName1;
…
typen memberNamen;
}
Example
Declaring a Structure Variable (Method 1)
Syntax
struct structName
{
type1 memberName1;
…
typen memberNamen;
} varName1 ,…, varNamen;
Example
Declaring a Structure Variable (Method 2)
Syntax
If structName has already been defined:
struct structName varName1 ,…, varNamen;
Example
Using a Structure Variable
Syntax
structVariableName.memberName
Example
Creating a Structure Type with typedef
Syntax
typedef struct structTagoptional
{
type1 memberName1;
…
typen memberNamen;
}
typeName;
Example
Declaring a Structure Type Variable
Syntax
If typeName has already been defined:
typeName varName1 ,…, varNamen;
The keyword struct is no longer required!
Example
Initializing a Structure Variable at Declaration
Syntax
If typeName or structName has already been defined:
typeName varName = {const1 ,…, constn};
or
struct structName varName = {const1 ,…, constn};