0

我在使用运行时确定的大小初始化双精度数组时遇到问题。

MyPoly MyPoly::operator *(const MyPoly& other)
{
    int newDegree = this->_degree + other._degree;
    double array [newDegree] ;
    fillArrayWithZeros(array, this->_degree + other._degree);

    PolyRep::iterator it1 = this->_poly->begin();
    PolyRep::iterator it2 = other._poly->begin();

    for (int i = 0; i <= this->_degree; ++i, ++it1)
    {
        for (int j = 0; j <= other._degree; ++j, ++it2)
        {
            array[i + j] += (*it1) * (*it2);
        }
        it2 = other._poly->begin();
    }
    return MyPoly(array, this->_degree + other._degree);
}

它在函数的第二行。如果我输入一个数字 - 10 它就可以了。没有编译错误,也没有运行时错误,但是当我调试程序时,我看到数组是空的。

问题是,在以下函数中,尽管数组的大小也在运行时确定,但初始化工作正常:

MyPoly MyPoly::operator +(const MyPoly& other)
{
    int bigDegree = (this->_poly->getDegree() > other._poly->getDegree()) ?
            this->_poly->getDegree() : other._poly->getDegree();

    double arr [bigDegree];

    PolyRep::iterator it1 = this->_poly->begin();
    PolyRep::iterator it2 = other._poly->begin();

    for (int i = 0; i <= this->_poly->getDegree(); ++i, ++it1)
    {
        arr[i] = *it1;
    }

    for (int i = 0; i <= other._poly->getDegree(); ++i, ++it2)
    {
        arr[i] += *it2;
    }

    return MyPoly(arr, bigDegree + 1);
}

两个函数都在同一个类中。

有人可以解释是什么问题吗

4

2 回答 2

2

在这两个代码中,您都在注销数组的末尾,这可能会导致任意不良行为。您需要在循环中使用<而不是,或者分配 2 个额外的插槽。<=

要回答您的问题,否则您将正确使用运行时大小的数组。

于 2012-09-05T23:15:39.170 回答
0

在一个代码中,您正在使用->_degree,而在另一个代码中,您正在使用->getDegree(). 这些真的是一回事吗?

于 2012-09-05T23:32:26.533 回答