2016-03-23 24 views
-3

我想做一個函數,修改一個int數組。但數組是動態的,指針和引用不起作用。這裏是一個例子如何傳遞一個動態數組參考c + +

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

首先這個'* int'是完全錯誤的 – DimChtz

+0

我的意思是INT *陣列XD我的手機 – James

+2

當您在做'&array'你得到一個指向*的指針*,它的類型是'int **',而不是你想要做的。另外,通過使用數組索引,實際上是對指針進行解引用:對於任何指針*或數組* * p和索引'i',表達式'p [i]'等價於'*(p + i)'。注意'*(p + i)'中的解引用操作符。 –

回答

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

如果你能說出你改變了什麼,以及爲什麼你改變了,那將會很好。只是顯示一些工作代碼並不能真正幫助解釋問題。 –

+0

@JoachimPileborg你是對的。我只是想,如果OP不明白我的答案中的某些內容,他會問​​,我會解釋他:) – DimChtz

+0

編輯和添加的代碼 – James