Structures
Structures allow you to create a new type of data consisting of several
entities collected under a single name.
For example, the following is a structure definition:
struct Contact
{
char name[20];
int number;
};
Contact is a new type, encompassing two different entities: the string
name and the variable
number.
If you want to declare a variable of type Contact (which we will also call a
structure), you can simply type:
Contact aContact;
To access the entities of which aContact consists, you need to use the dot
.
operator.
strcpy(aContact.name, "Mike");
assigns the string
"Mike" to
name.
Further, a structure can be assigned to another of the same type.
Contact anotherContact = aContact;
Such a statement results in each field within the assigned structure being
copied into the assignee’s.
Example
#include <iostream>
#include <cstring>
using namespace std;
struct Contact
{
char name[20];
int number;
};
void printContact(Contact c)
{
cout << "name: " << c.name << endl;
cout << "number: " << c.number << endl;
cout << endl;;
}
int main()
{
Contact aContact;
strcpy(aContact.name, "Mike");
aContact.number = 123456;
Contact anotherContact;
anotherContact = aContact;
cout << "aContact:" << endl;
printContact(aContact);
cout << "anotherContact:" << endl;
printContact(anotherContact);
}
Output
aContact:
name: Mike
number: 123456
anotherContact:
name: Mike
number: 123456