摘自:http://www.sudu.cn/info/html/edu/C/20070103/236588.html
一、你需要一个函数将一个数组赋值为等差数列,并将会在函数的外部使用他。
不合理:
int *GetArray( int n ) { int *p = new int[n]; for ( int i = 0; i < n; i++ ) { p[i] = i; } return p; } |
void GetArray( int *p, int n ) { for ( int i = 0; i < n; i++ ) { p[i] = i; } } |
class A { public: A( void ) {} ~A( void ) { delete []m_pPtr; } void Create( int n ){ m_pPtr = new int[n]; } private: int *m_pPtr; }; |
class A { public: A( void ) : m_pPtr(0){} ~A( void ) { Clear(); } bool Create( int n ){ if ( m_pPtr ) return false; m_pPtr = new int[n]; return ture; } void Clear( void ) { delete []m_pPtr; m_pPtr = 0; } private: int *m_pPtr; }; |
bool Create(int *a, int n ) { if ( m_pPtr ) return false; m_pPtr = new int[n]; for ( int i = 0; i < n; i++ ) { m_pPtr[i] = 3 / a[i]; } return true; } |
template class auto_array { public: explicit auto_array(_Ty *pPtr=0)throw():m_Ptr(pPtr){} ~auto_array(){delete[]m_Ptr;} void reset(_Ty *pPtr=0){if(pPtr!=m_Ptr){delete[]m_Ptr;m_Ptr=pPtr;}} _Ty* release(void){_Ty *pTemp=m_Ptr;m_Ptr=0;return pTemp;} private: auto_array(const auto_array&other){} auto_array& operator=(const auto_array& other){} _Ty *m_Ptr; }; bool A::Create(int *a, int n ) { if ( m_pPtr ) return false; auto_array PtrGuard( new int[n] ); for ( int i = 0; i < n; i++ ) { if ( 0 == a[i] ) { return false; } PtrGuard .get()[i] = 3 / a[i]; } m_pPtr = PtrGuard.release(); return true; } |
int aMatrix[4][4]; for ( int i = 0; i < 4; i++ ) { for ( int j = 0; j < 4; j++ ) { if ( i == j ) { aMatrix[i][j] = 1; } else { aMatrix [i][j] = 0; } } } |
int aMatrix[4 * 4]; for ( int i = 0; i < 4; i++ ) { for ( int j = 0; j < 4; j++ ) { if ( i == j ) { aMatrix[ i * 4 + j ] = 1; } else { aMatrix [ i * 4 + j ] = 0; } } } |
for( int i = 0; i < 4; i++ ) { for ( int j = 0; j < 4; j++ ) { aMatrix[ j * 4 + i ] = i * 4 + j; } } |
for( int i = 0; i < 4; i++ ) { for ( int j = 0; j < 4; j++ ) { aMatrix[i * 4 + j ] = j * 4 + i; } } |
void foo( float *pPoints[3] ) { float aPoint[3] = { 1.0f, 2.0f, 3.0f }; int nCount = (int)_msize( pPoints ); for ( int i = 0; i < nCount; i++ ) { pPoints[i][0] = aPoint[0]; pPoints[i][1] = aPoint[1]; pPoints[i][2] = aPoint[2]; } } |
struct POINT3 { float x, y, z; }; void foo( POINT3 *pPoints, int nCount ) { POINT3 Pt = { 1.0f, 2.0f, 3.0f }; for ( int i = 0; i < nCount; i++ ) { pPoints[i] = Pt; } } |
void foo( void ) { Data *p = new Data; CalcData( p ); delete p; } |
char Buf[sizeof(DATA)]; void foo( void ) { Data *p = new(Buf) Data; CalcData( p ); } |