Home Library Index Site Map� Links Contact About

Arrays


Simple static array.
// A simple static array.
const int SZ=3; // constant
int i, array[SZ];

// initialise
for(i=0; i<SZ; i++) array[i]=i;

// print
for(i=0; i<SZ; i++) cout<<array[i];
A constant must be used for the subscript .
Home Library Index Top

Simple dynamic array.
// A simple dynamic array.
int i, var=10;
int* array =new int[var];

// initialise
for(i=0;i<var;i++) array[i]=i;

// print
for(i=0;i<var;i++) cout<<array[i];

delete array;
Note that a variable can be used as a subscript.
Home Library Index Top

Simple static matrix.
// A simple static matrix.

const int SZ=3;
int i, j;

int array [SZ] [SZ];

//initialise
for(i=0 ;i<SZ ;i++)
for(j=0 ;j<SZ ;j++) array[i] [j] =j;

// print
for(i=0 ;i<SZ ;i++)
for(j=0 ;j<SZ ;j++) cout<<array[i] [j];
Home Library Index Top

Dynamic matrix.

// Only one subscript need be specified at runtime.

const int SZ=3;
int var=4, i, j;
int (*matrix)[SZ] = new int[var] [SZ];

for(i=0; i<var; i++)
for(j=0; j<SZ; j++) matrix[i] [j] =j;

for(i=0; i<var; i++)
for(j=0; j<SZ; j++) cout<<matrix[i] [j];

delete [] matrix;
Home Library Index Top

Dynamic Matrix.
// Dynamic matrix.
int i, rows=2, cols=3;

int**matrix =new int*[rows];
for(i=0; i< rows; i++) matrix[i]= new int[cols];

// initialise
for(i=0; i<rows; i++)
for(int j=0; j<cols; j++) matrix[i] [j] =j;

// print
for(i=0; i<rows; i++)
for(int j=0; j<cols; j++) cout<<matrix[i] [j];

// delete
for(i=rows;i>0; --i) delete [] matrix [i-1];

delete [] matrix;
This defines a 2 x 3 matrix.
It is allocated totally from the free store and both subscripts can be specified at runtime.

The line int** matrix =new int*[rows]; is key.
It means: a pointer to an array of ints with rows elements is assigned to matrix which is a pointer to a pointer to int.

Simple huh?... Isn't C++ fun :).
Home Library Index Top

  • An Array Class using overloaded
    operators and the STL exception
    handling

  • A Vector Class using a method
    based implementation and custom
    exception handling

STL Database
Arrays
Binary File Input / Output
Character Input
Containers
Standard Template Library
Streams
Templates
Utility Functions
Win32 Programming
Miscellaneous

 
copyright notice

Copyright Robert Mitchell. Last Revised : 22 June, 2000

e-mail me
Hosted by www.Geocities.ws

1