简体   繁体   中英

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

I'm trying to pass an array into my function calls for build_max_heap and max_heapify so I can modify the array after each call, but I receive an error saying "candidate function not viable: no known conversion from 'int [9]' to 'int *&'for 1st argument."

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

While array can be decayed to a pointer int* to be passed as a function argument, it the pointer cannot be passed as a "non-const reference" int*& , because it is immutable (it is a constant address). You could have passed it as a const reference like this:

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

However, this doesn't make much sense, you can simply pass the pointer by value (a copy of the address of the array), which results in the same: the variable at the caller wont be changed. The usual use case of const& parameters is to pass objects that are expensive to copy, such as std::string . This does not apply to pointers; making a copy of a pointer is as cheap as copying any basic variable.

You should change your functions to take the pointer by value:

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

also, correct the call to max_heapify inside build_max_heap , give it the correct number of arguments:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM