ECE 10
Dr. Klefstad
Dynamic Allocation of Arrays

Outline

Pointers and References


Arrays and Pointers

Limitations of Fixed-Size Arrays

Dynamic Allocation of Arrays

Arrays within Classes

The Copy Constructor

operator index


operator =

operator ==

Pointer Caveats

Extended Example

public: IntList( int newLength = DEFAULT_SIZE ) : maxLength( newLength ), curLength(0), buf( new int[newLength] ) { // assert( newLength > 0 ); } IntList( IntList & l ) : maxLength( l.maxLength ), curLength( l.curLength ), buf( new int[l.maxLength] ) { copy( buf, l.buf, l.curLength ); } int length() { return curLength; } void append( int value ) { if ( curLength == maxLength ) increaseArrayTo( maxLength + DEFAULT_SIZE ); buf[curLength++] = value; } void print( ostream & out ) { for ( int i = 0; i < curLength; i++ ) out << buf[i] << ' '; } int & operator [] ( int index ) { // assert( indexInBounds( index ) ); return buf[index]; } IntList & operator = ( IntList l ) { if ( maxLength < l.curLength ) increaseArrayTo( l.curLength ); copy( buf, l.buf, l.curLength ); curLength = l.curLength; return *this; } bool operator == ( IntList l ) { if ( curLength != l.curLength ) return false; for ( int i = 0; i < curLength; i++ ) if ( buf[i] != l.buf[i] ) return false; return true; } bool operator != ( IntList l ) { return ! operator == ( l ); } int indexOf( int value ) { for ( int i = 0; i < curLength; i++ ) if ( buf[i] == value ) return i; return -1; } void remove( int value ) { int i = indexOf( value ); if ( i != -1 ) buf[i] = buf[--curLength]; } IntList reverse() { IntList result(curLength); for ( int i = curLength - 1; i >= 0; i-- ) result.append( buf[i] ); return result; } ~IntList() { delete[] buf; } }; ostream & operator << ( ostream & out, IntList l ) { l.print( out ); return out; }