Skip to main content

Structs with Arrays

Sometimes, structs may need to store more complicated data. Consider how we might store all the marks for IPC144.

In IPC144 you have the following scores:

  • quizzes - 6 in total
  • labs - 9 in total
  • projects - 2 in total
  • tests - 2 in total

If you were to store all grades for a student along with the student's student number, how would you do this?

A struct with arrays

A struct can have arrays in it. This allows us to store arrays of information that is packaged together as one whole object.

struct Scores
{
int studentNumber;
float quizzes[6];
float labs[9];
float project[2];
float tests[2];
};

Initializing arrays inside a struct

For any array, we can initialize the arrays using array notations. Suppose we have a student with student number 123456 with the following scores:

  • quiz scores: 9.5, 10.0, 8.5, 7.0, 8.0, 7.5
  • lab scores: 1, 1, 1, 0.5, 0, 1, 1, 1, 1
  • project scores: 15.5, 12.5
  • test scores: 35.5, 43.5

We would initialize the IPCScores array

struct Scores student1= {  12345,
{9.5, 10.0, 8.5, 7.0, 8.0, 7.5}, //initializes quizzes
{1, 1, 1, 0.5, 0, 1, 1, 1, 1}, //initializes labs
{15.5, 12.5}, //initializes project
{35.5, 43.5} //initializes tests
};

For clarity I put the initializer for each data member on a separate line but this is not necessary. You simply need to put the inializers for each of the data members in a comma separated list.

Accessing data members

We extend our syntax of structs to access each array element. We use our instance variable then use the dot (.) operator to access our data member. If we happen to have a pointer to a struct we would use the arrow (->) operator instead. From there we can then use [] to access the appropriate element of the array.

For example:

	struct IPCScores student1 = {	12345,
{9.5, 10.0, 8.5, 7.0, 8.0, 7.5},
{1, 1, 1, 0.5, 0, 1, 1, 1, 1},
{15.5, 12.5},
{35.5, 43.5}
};

student1.quizzes[0] = 9.0; //changes the quiz 1 grade to 9.0

This can be visualized as:

struct with arrays

Summary

  • structs can have array data members
  • to access the array data member use . or -> notation (depending if you have an actual instance of a struct or pointer to a struct) then use the [] to access the element you are interested in.
  • entire arrays in a struct can be initialized using notation just like with arrays.