1. Computing & Technology

Discuss in my forum

C++ Tutorial - About Pointers

By , About.com Guide

10 of 10

Example of 2D Structure with Pointers
Example 5 creates a two dimensional array of structs, each holding a string and row and column coordinates of that struct in the array.
 // ex5.cpp
 
 #include <string>
 using namespace std;
 
 const maxrows=5;
 const maxcolumns=10;
 
 struct mapitem 
 {
   int row,column;
   string line;
   mapitem(int _row,int _column) {row=_row,column=_column,line='\0';}
 };
 
 typedef mapitem * col[maxcolumns];
 typedef col * gridtype[maxrows];
 
 int main(int argc, char* argv[])
 { 
   gridtype grid;
   int rowindex,colindex;
 
   for (rowindex=0;rowindex < maxrows; rowindex++) {
   // Allocate memory for columns in each row 
     grid[rowindex] = new col[maxcolumns];
     for (colindex=0;colindex < maxcolumns;colindex++)
     {
     // Hook up the grid to a new item
     *(grid[rowindex])[colindex] = new mapitem(rowindex,colindex) ;
     }
   }
 
   // Set the string for the top left corner etc
   (*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 5
This is a 2d grid of structs with pointers for each item and row to make it more flexible. Memory has to be allocated for
  1. Each Row.
  2. Each Item in each row.
And free them up when finished. (Not done). I used a constructor to initialise each item. The _ on the constructor argument names makes it easier to associate them with the object members.

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

©2012 About.com. All rights reserved.

A part of The New York Times Company.