When you declare a structure you are actually creating a new data type. The
data type is a compound type since it contains several built in or primitive
data types. Declarations of new structure data types can be made inside
or outside functions. The best place to declare them, however is BEFORE function
prototypes. This way they are available to be used in the prototypes or any
of the functions in the program. Once you have declare the new type you can
create as many variables of that type as you wish. Remember, just because
a data type exists doesn't mean you have a variable of that type to use in
your program. Think of the structure you declare the same way you think of
int, float, bool or char. These data types are build into C++ so you didn't
have to declare them, but the data type you created will work the same way
as these built in types.
Once the data type has been created you can define as many variables of that
type as you wish. These declarations go inside your functions. You declare,
lay out, the data type once and then use that data type the same way you use
any other variable data type. When creating an array of a structure data type,
the syntax becomes a little more challenging. Say we have the following data
type:
struct Student {
char firstName[15];
char lastName[15];
float gpa;
};
In main we can now declare an array of type Student:
int main() {
Student kishStudent[5];
return 0;
}
The above creates an array of 5 Student variables. Each element has 3 variables of its own:
kishStudent |
[0] |
[1] |
[2] |
[3] |
[4] |
firstName |
firstName |
firstName |
firstName |
firstName |
lastName |
lastName |
lastName |
lastName |
lastName |
gpa |
gpa |
gpa |
gpa |
gpa |
The code to get to each to use a member of an element is:
kishStudent[index].firstName;
kishStudent[index].lastName;
kishStudent[index].gpa;