2-d双数组无法初始化

时间:2011-01-11 20:10:00

标签: visual-c++ visual-c++-2008

我正在多次调用一个初始化二维双精度数组的函数。前三个呼叫成功,但第四个呼叫失败。代码是:

double **scmass;
double **scdv;
double **dvmatches;
double **zpp;

...

scmass = init_d2darr(numrow,numcol);
scdv = init_d2darr(numrow,numcol);
dvmatches = init_d2darr(numrow,numcol);
zpp = init_d2darr(numrow,numcol);

...

double ** init_d2darr(int isize, int jsize) {
int m,n;
printf("in array initialize 1\n");
printf("isize: %i\njsize: %i\n",isize,jsize);
/* how many rows */
double **arr = (double **)malloc(sizeof(double *) * isize);
printf("after row initialization\n");
if (arr == NULL) {
    printf("malloc failed for arr in init_d2darr.\n");
    return NULL;
}
else {
    /* now how many cols */
    for (m=0; m<=isize; m++) {
        arr[m] = (double *)malloc(sizeof(double) * jsize);
        if (arr[m] == NULL) {
            printf("malloc failed for arr[%d] in init_d2darr.\n",m);
            return NULL;
        }
        else {
            /* initialize all to zero */
            for (n=0; n<jsize; n++) {
                arr[m][n] = 0;
            }
        }
    }
}
printf("in array initialize 2\n");
return arr;

输出如下:

in array initialize 1
isize: 20
jsize: 21
after row initialization
in array initialize 2
in array initialize 1
isize: 20
jsize: 21
after row initialization
in array initialize 2
in array initialize 1
isize: 20
jsize: 21

程序实际上在调试模式下一直运行,但是,当我发布可执行文件并尝试运行它时,程序崩溃并且我收到错误“问题导致程序停止正常工作。请关闭程序。“我在使用Visual C ++ 2008 Express Edition的Windows Vista上。有人能给我任何建议吗?谢谢!

编辑:函数声明(在头文件中)是

double ** init_d2darr(int isize, int jsize);

2 个答案:

答案 0 :(得分:0)

class double_array {
    double* arr;
    int arrsize;
public:
    double_array(int newsize) {
        arr = new double[newsize];
        arrsize = newsize;
        for(int i = 0; i < arrsize; i++)
            arr[i] = 0;
    }
    double_array(const double_array& other) {
        arr = new double[arrsize = other.arrsize];
        for(int i = 0; i < arrsize; i++)
            arr[i] = other.arr[i];
    }
    double& operator[](int index) {
#ifdef _DEBUG
        if (index >= arrsize)
            throw std::runtime_error("Attempted to access array out of bounds!");
#endif
        return arr[index];
    }
    const double& operator[](int index) const {
#ifdef _DEBUG
        if (index >= arrsize)
            throw std::runtime_error("Attempted to access array out of bounds!");
#endif
        return arr[index];
    }
    int size() {
        return arrsize;
    }
    ~double_array() {
        delete[] arr;
    }
};
std::vector<double_array> scmass(numrows, numcols);
std::vector<double_array> scdv(numrows, numcols);
std::vector<double_array> dvmatches(numrows, numcols);
std::vector<double_array> zpp(numrows, numcols);

易。

答案 1 :(得分:0)

在你的外围for循环中:

for (m=0; m <= isize; m++) 

这应该是:

for (m=0; m < isize; m++)