C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - About Pointers

By David Bolton, About.com

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 will be on the advanced users of pointers.

Explore C / C++ / C#

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Example of 2D Structure with Pointers

©2009 About.com, a part of The New York Times Company.

All rights reserved.