Two Dimensional Arrays are a Myth

Do C language pointers frighten you? Good! They’re supposed to, mostly because few instructors bother explaining them well, but also because of the nomenclature: “Pointers point.” Regardless, if you shun pointers, as many C programmers do, you can fall back on array notation. It’s a useful alternative and a handy shortcut, but it’s completely bogus.

In other programming languages, those that borrow C syntax and notation, arrays are most likely 100 percent legit. In C, however, they’re a myth. This myth comes into play specifically for multi-dimensional arrays. To wit:

int table[3][2];

Whether you believe int array variable table to have 3 rows or 2 columns or 3 columns of 2 rows is irrelevant. Internally, the compiler sees only an int array with six elements. The expressions that access those elements are handy for you, but translate to the proper offset when the program runs. In other words, the compiler is just being nice.

The following code contains a 5-by-5 int array, grid. It’s a “magic square,” which contains values 1 through 25 in such a way that rows, columns — even diagonals — sum to the same value, 65.

#include <stdio.h>

int main()
{
    int grid[5][5] = {
        { 25, 13,  1, 19,  7},
        { 16,  9, 22, 15,  3},
        { 12,  5, 18,  6, 24},
        {  8, 21, 14,  2, 20},
        {  4, 17, 10, 23, 11}
    };
    int row,col;

    puts("Magic Square");
    for(row=0;row<5;row++)
    {
        for(col=0;col<5;col++)
            printf("  %2d",grid[row][col]);
        putchar('\n');
    }

    return(0);
}

The code is more readable as a two-dimensional array, using variables row and col to plug in values for the array grid. Internally, however, all that notation is translated into a single-dimension array; the [row] and [col] pieces merely calculate offsets within the single dimension array. Yes, you have to code more overhead if you plot the array that way, so why bother?

Well, because I have to prove it, which is why I bother.

Click here to view a modified version of the code, which plods through and adds all the rows, columns, and both diagonals to confirm that the array is indeed a magic square.

In next week's Lesson, I present the same code as a single-dimensional array.

Leave a Reply