Arrays Of Structures
Structures can contain any type of variable, pointer, array. Further,
structures can be nested. For example, given a structure called Contact:
struct Contact
{
char name[20];
int number;
};
one or more variables of type Contact can be included in another structure:
struct ContactCouple
{
Contact one;
Contact two;
};
In this case, the structure members are accessed through a multiple use of the
dot
. operator:
ContactCouple aCouple;
strcpy(aCouple.one.name, "Jane");
strcpy(aCouple.two.name, "Sam");
Contact array elements are accessed through
the
[] operator:
strcpy(arrayOfContact[0].name, "Mike");
arrayOfContact[0].number = 123456;
The address of a structure can be assigned to a structure pointer.
The second of the following statements assigns to
pContact the address of
the first element of the array
arrayOfContact
Contact *pContact;
pContact = arrayOfContact;
The address of a field of a structure can be assigned to a pointer:
int *pInt;
pInt = &aCouple.one.number;
Example
#include <iostream>
#include <cstring>
using namespace std;
struct Contact
{
char name[20];
int number;
};
struct ContactCouple
{
Contact one;
Contact two;
};
void printContact(Contact c)
{
cout << "name: " << c.name << endl;
cout << "number: " << c.number << endl;
cout << endl;;
}
int main()
{
ContactCouple aCouple; // nested structure
strcpy(aCouple.one.name, "Jane");
strcpy(aCouple.two.name, "Sam");
aCouple.one.number = 111222;
aCouple.two.number = 123321;
cout << "aCouple.one: " << endl;
printContact(aCouple.one);
cout << "aCouple.two: " << endl;
printContact(aCouple.two);
Contact arrayOfContact[10]; // array of structures
strcpy(arrayOfContact[0].name, "Mike");
arrayOfContact[0].number = 123456;
Contact *pContact; // pointer to a structure
pContact = arrayOfContact;
printContact(pContact[0]);
int *pInt; // pointer to a structure field
pInt = &aCouple.one.number;
cout << "pInt: " << *pInt;
}
Output
aCouple.one:
name: Jane
number: 111222
aCouple.two:
name: Sam
number: 123321
name: Mike
number: 123456
pInt: 111222