Reader small image

You're reading from  Learn C Programming. - Second Edition

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781801078450
Edition2nd Edition
Right arrow
Author (1)
Jeff Szuhay
Jeff Szuhay
author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay

Right arrow

Chapter 12: Working with Multi-Dimensional Arrays

Chapter 11, Working with Arrays, is essential for understanding the concepts presented in this chapter. Please read through and ensure you understand that chapter before reading this one.

In Chapter 11, Working with Arrays, we explored a one-dimensional (1D) array, where an array is a contiguous group of the same data type accessed via a base name and an index. In this chapter, we will extend the concept of arrays from one dimension to many dimensions. Multi-dimensional arrays occur in a myriad of objects that we deal with in daily life—from a simple checkers board or chessboard, a multiplication table, or the pixels on a screen to more complex three-dimensional (3D) objects, such as volumetric spaces. We will see that these are simple extensions of 1D arrays.

The following topics will be covered in this chapter:

  • Going beyond 1D arrays to multi-dimensional arrays
  • Declaring and initializing multi-dimensional...

Technical requirements

Continue to use the tools you chose from the Technical requirements section of Chapter 1, Running Hello, World!.

The source code for this chapter can be found at https://github.com/PacktPublishing/Learn-C-Programming-Second-Edition/tree/main/Chapter12.

Going beyond 1D arrays to multi-dimensional arrays

It is common to present a two-dimensional (2D) array as an array of a 1D array. Likewise, a 3D array can be thought of as an array of 2D arrays. Furthermore, an N-dimensional array can be thought of as an array of (N – 1)-dimensional arrays.

This approach, while mathematically correct, may not provide a useful, working framework for multi-dimensional arrays. Therefore, before we can address the C syntax for declaring, initializing, and accessing multi-dimensional arrays, a proper conceptual framework must be developed. With that firmly understood, we can then delve into C's syntax for multi-dimensional arrays.

Revisiting 1D arrays

An array of one dimension is a block, or contiguous grouping, of a specified data type accessed via a base name; each element is then accessed via an offset from that base name. That offset is also called the index.

A 1D array may be called a vector in some domains, while in others...

Declaring and initializing multi-dimensional arrays of various dimensions

With a firm, conceptual grasp of multi-dimensional arrays, we can now explore the C syntax for declaring them. As we move from two to more dimensions, we will continue to use array1D, array2D, array3D, and array4D to match the previous section. As each array is declared, pay particular attention to the order in which the array indices appear in each definition. In general, the highest-order dimension appears at the leftmost side and the lowest-order dimension (in our example, array1D) appears in the rightmost position.

Before we begin, we'll define some size constants, as follows:

enum {
  size1D = 5,
  size2D = 4,
  size3D = 3,
  size4D = 7
};

In each of our declarations, we could simply use literal numbers to specify each dimension's size. Instead, we'll use the size1D, size2D, size3D, and size4D constants, not just in this section...

Accessing elements of multi-dimensional arrays of various dimensions

To access an array element using array notation, we must be consistent in using both the dimensions of the array and a valid range of offsets for each dimension.

To access an element of an array, we would use the [ and ] notation for each of its offsets in each dimension. Remember that C indices are zero-based. It is better to think of them as offsets from the array base—for example, the column offset for the first element in a 1D array is [0]; the row offset for the first row of a 2D array is [0][x]; the layer offset for the first layer of a 3D array is [0][y][x]. Putting this knowledge to work, let's access the third element of our various arrays, as follows:

int third;
first = array1D[2];       // third element.
first = array2D[0][2];    // third element of 1st row.
first = array3D[0][0][2]; // third element of 1st layer and 
...

Manipulating multi-dimensional arrays using loops within loops

There are many ways in which to use loops to access elements within multi-dimensional arrays. The best way, however, is to use nested for()… loops. In a nested loop, the outermost loop contains one or more loops within it, nested such that the outer loop completely contains the inner loop. When using nested loops, the outermost loop manipulates the index of the highest-order dimension, while the innermost loop manipulates the index of the lowest-order dimension. We will explore 2D and 3D looping. It is then simple to extend the nested loops to as many as are needed for an array with more than three dimensions.

When nesting loops, it is a common convention to use variables named i, j, k, and so on to hold the values of the array offsets, with i being the first-order dimensional offset, j being the second-order dimensional offset, k being the third-order dimensional offset, and so on. This convention is optional...

Using multi-dimensional arrays in functions

Now that we can declare, initialize, and access arrays of many dimensions, we are ready to create functions to manipulate them. We'll proceed as follows:

  1. First, let's create a function to initialize a 2D array and a function to initialize a 3D array, as follows:
    void initialize2DArray( int col, int row, int array[row][col] ){
      for( int j = 0 ; j < row ; j++ )  {// j : 0..(row-1)
        for( int i = 0 ; i < col ; i++ )  {// i : 0..
                                           // (col-1)
          array[j][i] = (10*(j+1)) + (i+1);
        }
      }
    }
    void intialize3DArray( int x, int y, int z, int array[z][y][x] ){
      for( int k...

Summary

In this chapter, we have taken the basic idea of a 1D array from Chapter 11, Working with Arrays, and extended it to 2D, 3D, and even N-dimensional arrays. A conceptual basis for multi-dimensional arrays has been developed. Then, we have seen how to declare, initialize, access, and iterate over multi-dimensional arrays using C syntax. Emphasis was placed on zero-based array indices (more appropriately known as offsets) and on the somewhat peculiar order in which indices are specified—left to right from the highest-order dimension to the lowest-order dimension. This order, however, lends itself somewhat elegantly to nested looping to iterate over multi-dimensional arrays. This chapter may have seemed long; the intent was to demonstrate how consistently the same concepts can be applied from 1D arrays to N-dimensional arrays.

In this chapter, we have not spent too much time delving into what the base of an array is. Before we can get a greater understanding of array...

Questions

  1. What is another name for a 1D array?
  2. What is another name for a 2D array?
  3. What are some possible real-life representations of a 3D array?
  4. In a 2D or 3D array, which index represents the x axis or column number?
  5. Is it more desirable to use CLA or VLA definitions for multi-dimensional arrays?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn C Programming. - Second Edition
Published in: Aug 2022Publisher: PacktISBN-13: 9781801078450
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay