1. Computing & Technology

Discuss in my forum

C Tutorial - About Pointers

By , About.com Guide

10 of 10

Example of 2D Structure with Pointers
#define MAXROWS 5
#define MAXCOLUMNS 10
#define MAXLINELENGTH 80

typedef struct mapitem
{
  int row,column;
  char * line;
};

typedef struct mapitem * pmapitem;
typedef pmapitem row[MAXCOLUMNS];
typedef row * gridtype[MAXROWS];

int main(int argc, char* argv[])
{
  gridtype grid;
  pmapitem tempitem;
  int rowindex,colindex;

  for (rowindex=0;rowindex < MAXROWS; rowindex++) {
    
    grid[rowindex]=(row *)malloc(sizeof(row)) ;
    for (colindex=0;colindex < MAXCOLUMNS;colindex++)
    {
       
        tempitem = (pmapitem)malloc(sizeof(struct mapitem)) ;
        tempitem->row= rowindex;
        tempitem->column= colindex;

       
      tempitem->line = (char *)malloc(MAXLINELENGTH+1) ;
     /* clear the string */
    *tempitem->line ='\0';

    
    *(grid[rowindex])[colindex] = tempitem;
     }
   }

    
    (*grid[0][0])->line="Top Left Corner";
    (*grid[MAXROWS-1][0])->line="Bottom Left Corner";
    (*grid[0][MAXCOLUMNS-1])->line="Top Right Corner";
    (*grid[MAXROWS-1][MAXCOLUMNS-1])->line="Bottom Right Corner";
    return 0;
}
Download Example 6
This is a 2d grid of structs with pointers for each item and row to make it more flexible. Memory must be allocated for
  1. Each Row.
  2. Each Item in each row.
  3. Each Line (the char * field) in each item.
And free them up when finished. (Not done).

This completes this lesson. The next lesson will be on the advanced users of pointers.

©2012 About.com. All rights reserved.

A part of The New York Times Company.