程序中数组太大,有v[3579][4000],编译时报错。于是改为动态分配类存.
this problem often appears on Windows because Windows has limit on stack memory.
if you define v[5], you use stack memory.
if you use new or malloc to create array, you use heap memory which is normally
bigger.
If you code in C++, why do not you use new which is made by malloc?
two ways to do this.
1. use 1D array to replace 2D array;
2. create 2D array
double ** twoDArrayAlloc(const int r, const int s)
{
double ** x = new double*[ r ];
for ( int i = 0; i < r; ++i )
{
x[ i ] = new double[ s ];
}
return x;
}
void TwoArrayFree( const int r, double ** & x)
{
if ( x == NULL ) //without this, the code can crash in the following for loop
{
return;
}
for ( int i = 0; i < r; ++i )
{
delete[] x[ i ];
}
delete[] x; x = NULL; //to avoid crash when duplicate delete is made
}
if you want to have a better one, do this,
#include <new>
#include <iostream>
double ** twoDArrayAlloc(const int r, const int s)
{
double ** x( 0 );
try
{
x = new double*[ r ];
for ( int i = 0; i < r; ++i )
{
x[ i ] = new double[ s ];
}
}
catch( bad_alloc const & exception )
{
std::cout << " 2D array allocation failed because of "<< exception.what() <<endl;
}
return x;
}
[ 此帖被steinlee在2009-11-13 08:52重新编辑 ]