簡體   English   中英

如何通過引用 C++ 將動態數組傳遞出函數

[英]How to pass a dynamic array out of function by reference c++

我正在嘗試制作一個修改 int 數組的函數。 但是數組是動態的,指針和引用不起作用。 這是一個例子

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

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

我知道這是一個愚蠢的例子,但我手頭沒有代碼!

我認為問題在於它應該是函數中的雙指針,但我不知道如何使用帶有雙指針的引用。

編輯 --------------------------------------------- 這是代碼。 我找到了!

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

這應該有效:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM