从函数返回数组会产生意外结果C ++

我试图与Qt创建者学习C ++,现在我无法输出正确的结果。 我的程序应该从QTableWidget读取数字并输出最低的数字。有时它可以工作,但是经常有像201-e302这样的东西。我不知道为什么

这是我的代码:

    QPair<int, double*> Widget::count()
{
    double *arr = new double[0];
    bool ok;
    int len = 0;
 //Reading numbers from QTablewidget
    for (int row = 0; row < ui->table->rowCount(); row++)
        for (int col = 0; col < ui->table->columnCount(); col++)
        {
            if(ui->table->item(row, col) and
                    ui->table->item(row, col)->text().length() != 0)  
            {
                double *temp = new double[len + 1];
                for (int j = 0; j < len; j++)
                {
                    temp[j] = arr[j];
                }
                temp[len] = ui->table->item(row, col)->text().toDouble(&ok);
                arr = temp;
                delete [] temp;
                len++;
            }
            else
            {
                QPair<int, double*> res = qMakePair(0, arr);
                QMessageBox::information(this, "Error", "Fill every cell");
                return res;
            }
        }
//
    QPair<int, double*> res = qMakePair(len, arr);
    return res;
}

void Widget::on_min_but_clicked()
{
    int len = count().first;
    double* arr = count().second;
    if (len != 0)
    {
        double min = arr[0];
        for (int i = 0; i < len; i++)
        {
            if (arr[i] < min)
            {
                min = arr[i];
            }
        }
        ui->min_lineedit->setText(QString::number(min));
    }
}
评论
  • 回忆终止
    回忆终止 回复

    在此代码段中,您正在分配一个新数组,为该数组分配一个指针,然后删除该数组。

    double *temp = new double[len + 1];
    arr = temp;
    delete [] temp;
    

    This leaves arr with a dangling pointer to deleted memory.