- The definition of a structure and the creation of variables can
be combined into a single declaration, as well. Just list the
variables after the structure definition block (the blueprint), and
before the semi-colon:
struct structureName
{
// data elements in the structure
} variable1, variable2, ... , variableN;
- Example:
struct fraction
{
int num; // the numerator of the fraction
int denom; // the denominator of the fraction
} f1, fList[10], *fptr; // variable, array, and pointer created
- In fact, if you only want structure variables, but don't plan to
re-use the structure type (i.e. the blueprint), you don't even need
a structure name:
struct // note: no structure NAME given
{
int num;
int denom;
} f1, f2, f3; // three variables representing fractions
- Of course, the advantage of giving a structure definition a
name is that it is reusable. It can be used to create structure
variables at any point later on in a program, separate from the definition
block.
- You can even declare structures as variables inside of other structure
defintions (of different types):
struct date // a structure to represent a date
{
int month;
int day;
int year;
};
struct employee // a structure to represent an employee of a company
{
char firstName[20];
char lastName[20];
struct date hireDate;
struct date birthDate;
};
- And, typedef can be used to create an actual type
name, which can be used to declare variables without repeating the
keyword struct:
typedef struct date
{
int month;
int day;
int year;
} Date; // "Date" is now a type name
/* ------------------ */
Date d1, d2, d3; // d1, d2, and d3 are now Date variables
// keyword struct was not necessary to declare
- Earlier, we saw an example of a structure variable used within another
structure definition
typedef struct date // making it a typedef
{
int month;
int day;
int year;
} Date; // so that "Date" is the type name
struct employee
{
char firstName[20];
char lastName[20];
Date hireDate; // using the typedef "Date" to declare
Date birthDate;
};
- Here's an example of initializing all the data elements for one
employee variable:
struct employee emp; // emp is an employee variable
// Set the name to "Alice Jones"
strcpy(emp.firstName, "Alice");
strcpy(emp.lastName, "Jones");
// set the hire date to March 14, 2001
emp.hireDate.month = 3;
emp.hireDate.day = 14;
emp.hireDate.year = 2001;
// sets the birth date to Sept 15, 1972
emp.birthDate.month = 9;
emp.birthDate.day = 15;
emp.birthDate.year = 1972;
- Here's an example of an employee initialization using our shortcut
initializer form:
struct employee emp2 =
{ "John", "Smith", {6, 10, 2003}, {2, 19, 1981} };
// John Smith, whose birthday is Feb 19, 1981, was hired on June 10, 2003
- struct2.c -- See
examples of nested structure access here