gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:31:57 24 4
gpt4 key购买 nike

我在使用运行时确定的大小初始化 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com