Arrays In Structures
Structures can contain arrays and pointers.
Given a structure representing a pupil:
struct Pupil
{
char name[20];
int gradesArray[10]; // array of grades in ten different subjects
Pupil *pStudyingMate; // points to the studying mate of this pupil
};
The structure contains the pupil's name and the pupil's grades.
It is assumed that every pupil has a studying mate,
whose corresponding structure is pointed to by
pStudyingMate. Given a
Pupil structure:
Pupil pupil1;
its elements can be accessed through the dot
. operator:
strcpy(pupil1.name, "Jake");
this also holds for array elements:
pupil1.gradesArray[0] = 5;
Pointers within structures can contain the address of any type of variable,
including structures of the same type as the one containing the pointer:
Pupil pupil2;
pupil2.pStudyingMate = &pupil1;
The statement above assigns the address of
pupil1
to the
pStudyingMate pointer within
pupil2.
Example
#include <iostream>
#include <cstring>
using namespace std;
struct Pupil
{
char name[20];
int gradesArray[10];
Pupil *pStudyingMate;
};
// prints structure's contents
void printPupil(Pupil aPupil)
{
cout << "name: " << aPupil.name << endl;
cout << "grades: ";
for (unsigned int i = 0; i <= 9; i++)
cout << aPupil.gradesArray[i] << " ";
cout << endl;
if(aPupil.pStudyingMate != NULL)
cout << "Studying mate: " << (aPupil.pStudyingMate)->name << endl;;
cout << endl;
}
// initialize to 0 array of grades
void initializaGradesArray(Pupil &p)
{
for (unsigned int i = 0; i <= 9; i++)
p.gradesArray[i] = 0;
}
int main()
{
Pupil pupil1, pupil2; // structures' declaration
// structures initialization
strcpy(pupil1.name, "Jake");
initializaGradesArray(pupil1);
strcpy(pupil2.name, "Mary");
initializaGradesArray(pupil2);
pupil1.pStudyingMate = &pupil2; // Mary is Jake's studying mate
pupil2.pStudyingMate = &pupil1; // Jake is Mary's studying mate
printPupil(pupil1);
printPupil(pupil2);
}
Output
name: Jake
grades: 0 0 0 0 0 0 0 0 0 0
Studying mate: Mary
name: Mary
grades: 0 0 0 0 0 0 0 0 0 0
Studying mate: Jake