Puzzle 2D4


Display a 2D integer array: Pointer Style

[E-6] (Skip this puzzle if you have not yet seen pointer arithmetic.)

Write a function that prints the elements of a 2D integer array. Write one row of the the array per output line on the monitor. The function prototype shows a parameter that is a pointer to the first element of the array:

void print2DArray ( int nrows, int ncols, int *x);

Inside the function body use an expression like this to access the array elements:

*(x+ncols*r+c)

This means:

If the above makes no sense: review pointers and pointer arithmetic.

Here is a program skeleton. Notice how the array is initialized in main():

#include <stdio.h>
#include <stdlib.h>

/* Puzzle D04-- print a 2D integer array */
void print2DArray ( int nrows, int ncols, int *x)
{
}

int main()
{
  int x[3][7] = { { 0,  1,  2,  3,  4,  5,  6},
                  { 7,  8,  9, 10, 11, 12, 13},
                  {14, 15, 16, 17, 18, 19, 20} };
     
  /* Print the array using our function */
  print2DArray( 3, 7, (int *)x );
  
  printf("\n");
  return 0;
}

main() declares the array as a two-dimensional array. In main storage it is a sequential block of ints which may be accessed through a pointer.



Previous Page        Answer         Next Page         Home