• 3892阅读
  • 2回复

大师帮忙——动态分配类存 [复制链接]

上一主题 下一主题
离线friday1203
 
只看楼主 倒序阅读 楼主  发表于: 2009-11-12
    程序中数组太大,有v[3579][4000],编译时报错。于是改为动态分配类存,但是不知道该怎样分配一个二维数组。在网上搜了下,写了这样一个函数,不知道是不是对的。那位大师能教教我:
#include <iostream>
double **TwoArrayAlloc(int r, int s)
{
        double **x;
        int       n;

        x=(double **)malloc(r*sizeof(double*));
//为较高的维分配空间(也可以理解为二维数组的“行”)


       for(n=0; n<s; ++n)
            x[n]=(double *)malloc(sizeof(double));
//用循环为较低的维分配空间(也可以理解为二维数组的“列”)
       return x;
}

void TwoArrayFree(double **x)
{

         free(x);
}
离线steinlee

只看该作者 1楼 发表于: 2009-11-12
程序中数组太大,有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重新编辑 ]
Looking for remote C/C++ and Qt 兼职
离线friday1203
只看该作者 2楼 发表于: 2009-11-12
不胜感激!Thank you very much!
快速回复
限100 字节
 
上一个 下一个