如何通过引用c ++将动态数组传递出函数

时间:2016-03-23 12:30:18

标签: c++ arrays pointers reference

我正在尝试创建一个修改int数组的函数。但是数组是动态的,指针和引用不起作用。这是一个例子

void addToArray (*int array, int position, int value) {
   *array[position] = value;
}

int *array = new int[10];
addToArray (&array, 0, 10); //crashes

我知道这是一个愚蠢的例子,但我没有代码可以提供!

我认为问题在于它应该是函数中的双指针,但我不知道如何使用带双指针的引用。

EDIT -------------------------------------------- 这是代码。我找到了它!

void MainWindow::on_pushButton_2_clicked()
{
    int *currentBuffer = new int[numberOfNodes^2];

    this->addToBuffer(&currentBuffer, 1, 0, numberOfNodes);
    qDebug() << "Finished Initial Add";
    for (int i = 0; i < numberOfNodes; i++) {
        qDebug() << currentBuffer[i];
    }
}

void MainWindow::addToBuffer(int *output[], int node, int position, int size) {
    qDebug() << "addToBuffer";
    for (int i = size * position; i < (size * (position + 1)); i++ ){
        qDebug() << "Iteration:" << i;
        if (ui->tableWidget->item(i, node)->text() != "-") {
            *output[i] = ui->tableWidget->item(i, node)->text().toInt();
        } else {
            *output[i] = 1000;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

这应该有效:

void addToArray (int *array, int position, int value) {
    // removed * because array is already a pointer
    array[position] = value;
}

int *array = new int[10];
addToArray (array, 0, 10);

编辑:

void MainWindow::on_pushButton_2_clicked()
{
    int *currentBuffer = new int[numberOfNodes^2];

    this->addToBuffer(currentBuffer, 1, 0, numberOfNodes);
    qDebug() << "Finished Initial Add";
    for (int i = 0; i < numberOfNodes; i++) {
        qDebug() << currentBuffer[i];
    }
}

void MainWindow::addToBuffer(int *output, int node, int position, int  size) {
      qDebug() << "addToBuffer";
      for (int i = size * position; i < (size * (position + 1)); i++ ){
          qDebug() << "Iteration:" << i;
          if (ui->tableWidget->item(i, node)->text() != "-") {
               output[i] = ui->tableWidget->item(i, node)->text().toInt();
          } else {
              output[i] = 1000;
          }
      }
  }