A Single-Dimension Array Pretends to be Two-Dimensions

Multi-dimension array notation is just a handy shortcut for you, the human programmer. Internally, an array is a single-file line of values, one marching after another. The dimensional aspect helps humans organize the array’s data, but all that organization is superficial.

In the following code, the grid[] array is declared with only one dimension, though it’s still a magic square. The manipulations performed use single-array calculations to pretend that two dimensions are present, yielding the same results as from a 2D array, but requiring a lot more math and overhead:

#include <stdio.h>

int main()
{
    int grid[25] = {
        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 x;

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

    for(x=0;x<5;x++)
        printf("Sum of row %d: %d\n",
                x+1,
                grid[(x*5)+0]+
                grid[(x*5)+1]+
                grid[(x*5)+2]+
                grid[(x*5)+3]+
                grid[(x*5)+4]
              );

    for(x=0;x<5;x++)
        printf("Sum of column %d: %d\n",
                x+1,
                grid[0+x]+
                grid[5+x]+
                grid[10+x]+
                grid[15+x]+
                grid[20+x]
              );

    printf("Sum of diagonal NW-SE: %d\n",
            grid[0]+
            grid[6]+
            grid[12]+
            grid[18]+
            grid[24]
          );

    printf("Sum of diagonal SW-NE: %d\n",
            grid[4]+
            grid[8]+
            grid[12]+
            grid[16]+
            grid[20]
          );

    return(0);
}

The code runs identically to last week’s example, but it’s a lot messier! I had to hand-code all those values to simulate the 2D array when adding rows, columns, and diagonals. That’s definitely not the point of programming. In fact it’s just silly because even a mediocre programmer would instinctively create a 2D array and use its nomenclature to perform the calculations.

Still the point is that all arrays, no matter how you declare them, are stored internally as a single line of values. Multi-dimensional array notation is for your convenience and, I must add, to make your code more readable.

So, everything is just wonderful! Except for a problem you’d only discover when you must send a multidimensional array to a function. In that situation, you must either continue to use a single-dimension array or resort to ugly ** pointer notation.

Fret not!

In next week’s Lesson, I demonstrate code that uses a function to validate a magic square grid without requiring pointer notation.

Leave a Reply