Book
Collection
Click for Table of Contents
© 2025 by Rance D. Necaise
C Primer for Python Programmers
Copyright © 2025
Rance D. Necaise

9.5 Arrays of Records

While single struct variables can be useful, there are many applications that require a collection of records. An array of structs or records is ideal for these applications. For example, suppose we need store a collection of addresses. We could create an array of Address structs the same as we would do when working with a collection of integer or floating-point values.

Defining the Array

To illustrate an array of records, suppose we want to represent a triangle, which consists of three vertices. We can define an array of Point structs with 3 elements to represent the triangle

Figure 9.5.1. An array of Point structs.
  1. struct Point triangle[3];

which can be visualized as shown in Figure 9.5.1. Here, each element of the array contains a Point struct variable. If we need to access an entire struct variable within an element of the array, we can do so by specifying the appropriate subscript. For example,

  1.   struct Point vertex = triangle[0];

creates a new Point struct named vertex and initializes it with the contents of the struct variable in the first element of the array.

Accessing Struct Fields

To access an individual field within a struct stored in an array element, we use the expression:

  1. triangle[1].x = 0;

which will assign 0 to the x field of the Point struct in the second element. Suppose we want to initialize all of the vertices to 0, we can use a for loop as shown below

  1. for(int i = 0; i < 3; i++) {
  2.   triangle[i].x = 0;
  3.   triangle[i].y = 0;
  4. }

which results in the following

As an alternative, we could initialize a Point struct with both fields set to 0 and then assign the struct to each element of the array

  1. struct Point init = {.x = 0, .y = 0};
  2. for(int i = 0; i < 3; i++) {
  3.   triangle[i] = init;
  4. }

Struct Pointers

If you need to get the address of a struct variable stored in an array, you simply take the address of the specific array element:

  1. struct Point *pt = &triangle[2];

which results in the following

Given the pointer, pt, we can access the fields of the struct in the last element through the pointer instead of the array subscript. For example, we can change the x- and y-coordinates of that point:

  1. pt->x = 15;
  2. pt->y = -3;

which updates the array with the following:

The triangles.cc sample program below provides a real-world example of using an array of Point structs to represent a triangle.

Program Listing
Testing for Right Triangles
Question 9.5.1