Shift and Verify a Magic Square

Last week’s Lesson showed how to shift a column of numbers in an array grid. The array just happens to be a magic square. So the puzzle is to run the array through the confirm_magic() function, which was presented in a previous week’s Lesson. Seems easy.

The problem, however, is that the confirm_magic() function assumes that you’re passing a single-dimension int array. In last week’s Lesson, however, the array is declared in two dimensions:

    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}
    };

You cannot pass a 2D array to a function unless you use ** pointer notation, which many C programmers avoid. And, as you can see above, I didn’t declare the array as a set of pointers.

The confirm_magic() function consumes a single-dimension array, so my solution was to create a second array g[] and copy the data from grid[][] into that array. This process takes place as the original array is displayed after moving column 0:

/* display grid */
    puts("New Magic Square");
    x = 0;
    for(row=0;row<5;row++)
    {   
        for(col=0;col<5;col++)
        {   
            printf("  %2d",grid[row][col]);
            /* build array for function */
            g[x] = grid[row][col];
            x++;
        }
        putchar('\n');
    }

As the nested for loops plow through the grid[][] array, each element is stuffed into array g[]:

g[x] = grid[row][col];

After the array is filled, it’s passed to the confirm_magic() function, as it’s a single-dimension array and the function can deal with it just fine.

Click here to view the full code.

You could modify the code further, so that it shuffles through all the rows and columns, each time confirming that the square remains magical. That’s an exercise you can attempt on your own. The point of this Lesson is to demonstrate a quick-and-dirty shortcut to pass a 2D array to a function that gobbles only 1D arrays — without having to resort to pointer notation.

Leave a Reply