struct is to organize variable names. For example,
I may have a name, an address and a phone number associated with
a student. To store these pieces of information, I could do the
following variable definitions:
char student_name[NAMESIZE]; char student_phone[PHNUMSIZE]; char student_address[ADDRSIZE];
But this gets tedious if I want to track information for two students
concurrently. So, instead of defining individual variables, I can
define a nameless struct:
struct
{
char name[NAMESIZE];
char phone[PHNUMSIZE];
char address[ADDRSIZE];
} student;
Note that this is a variable definition, not a class definition!
The name of the variable is student, and it so happens to have
components called name, phone and address in it.
If I want to keep track of another student, I can change the definition as follows:
struct
{
char name[NAMESIZE];
char phone[PHNUMSIZE];
char address[ADDRSIZE];
} studentA, studentB;
Now I have two variables of the same structure: studentA and
studentB. If I want to compare the names of the students, I can
do the following:
if (strncmp(studentA.name, studentB.name, NAMESIZE) < 0)
{
// ...
}
The main drawback of this approach is that the struct is not
named. As a result, I cannot refer to the structure of a student record
explicitly. This also means that I cannot use it as to specify a parameter,
or to create new student records elsewhere in the program.
Copyright © 2006-08-30 by Tak Auyeung