簡體   English   中英

將指向數組的指針傳遞給函數(C ++)

[英]Passing pointer to an array into a function (C++)

我正在嘗試將數組傳遞給我的函數調用build_max_heap和max_heapify,所以我可以在每次調用后修改數組,但是我收到一條錯誤,說“候選函數不可行:沒有已知的從'int [9]'轉換為' int *&'為第一個參數。“

#include <iostream>
#include <string>
using namespace std;

void build_max_heap(int*& array, int size);
void max_heapify(int*& array, int size, int index);


void build_max_heap(int*& array, int size)
  {
      for(int i = size/2; i>=0; i--)
      {
          max_heapify(array, i);
      }
  }


void max_heapify(int*& array, int size, int index)
  {
      int leftChild = 2*index+1;
      int rightChild = 2*index+2;
      int largest;
      int heap_size = size;

      if( leftChild <= heap_size && array[leftChild] > array[index])
          largest = leftChild;
      else
          largest = index;

      if(rightChild <= heap_size && array[rightChild] > array[largest])
          largest = rightChild;

      if(largest != index) {
          int tempArray = array[index];
          array[index] = array[largest];
          array[largest] = tempArray;
          max_heapify(array, heap_size, largest);
      }

  }

int main()
{
      int array[]={5,3,17,10,84,19,6,22,9};
      int size = sizeof(array)/sizeof(array[0]);

      build_max_heap(array, size);

      return 0;
}

int array[]={5,3,17,10,84,19,6,22,9};

雖然array可以衰減為指針int*以作為函數參數傳遞,但指針不能作為“非const引用” int*&傳遞,因為它是不可變的(它是一個常量地址)。 您可以將它作為const引用傳遞,如下所示:

void max_heapify(int* const& array, int size, int index)
//                    ^^^^^^

但是,這沒有多大意義,您可以簡單地按值傳遞指針(數組地址的副本),這會導致相同的結果:調用者的變量不會被更改。 const&參數的通常用例是傳遞復制成本高的對象,例如std::string 這不適用於指針; 制作指針的副本與復制任何基本變量一樣便宜。

您應該更改函數以按值獲取指針:

void build_max_heap(int* array, int size)
void max_heapify(int* array, int size, int index)

同時,糾正調用max_heapifybuild_max_heap ,給它正確的參數個數:

void build_max_heap(int* array, int size)
{
   for(int i = size/2; i>=0; i--)
   {
       max_heapify(array, size, i);  // <-- 3 arguments
   }
}

暫無
暫無

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

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