C++ : Array no been initialized when size is determined in runtime

标签 c++

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

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);
}

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

谁能解释一下这是什么问题

最佳答案

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

为了回答您的问题,您在其他方面正确使用了运行时大小的数组。

关于C++ : Array no been initialized when size is determined in runtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12290999/

相关文章:

c++ - 基于另一个数据成员的类数据成员类型?

c++ - 检查值是否已经存在于 multimap C++ 中

c++ - 如何正确编写模板模板参数?

C++ - 如何从一个类的构造函数中初始化一个单独类的构造函数?

c++ - 在 C(也是 C++)中, '&' 运算符如何同时用作地址运算符和按位运算符?由于 C 不支持运算符重载

C++ Lua 错误处理

c++ - 覆盖矩阵中 vector 对象的代理类中的赋值运算符?

c++ - Regex\w 在 C++11 中转义

java - 字符串的有序固定长度组合

c++ - 将子类作为父类传递给方法