how does int*& variableName work ?

52 views Asked by At

My professor gave us the following code but i don't fully understand how int*& works. My understanding is that the selectionSort function is passing back the address of the memory location where the array starts.

void SelectionSort(int* nums, unsigned int N, int*& SortedNums);
void SelectionSort(int* nums, unsigned int index);


  int main(){
  const unsigned int size = 12;
  int array[size] = {3,5,7,13,31,56,8,4,2,5,7,4};
  int* sorted;
  cout << "in main: " << &sorted << endl;

  SelectionSort(array, size, sorted);


  for( unsigned int i =0; i <size  ; i++){
  cout <<  *(sorted+i) << endl;
  }
  delete [] sorted;

  return 0;
  }

void SelectionSort(int* nums, unsigned int N, int*& SortedNums){
     cout << "in fucnt: " << &SortedNums<< endl;

     SortedNums = new int[N];
     for(unsigned int i= 0 ; i < N ; i++ ){
         *(SortedNums +i) = *(nums + i);
     }

  unsigned int numb_of_indexes = N-1; 


 SelectionSort(SortedNums, numb_of_indexes);
 }

 void SelectionSort(int* nums, unsigned int index){
     if(index ==1 ) return;

     int smallestindex = smallestIndex(nums, index);
     Swap(nums, smallestindex);
     SelectionSort(nums+1, index-1);
 }
2

There are 2 answers

0
Galik On BEST ANSWER

Consider this:

void func1(int* ip)
{
    // in here you have a COPY of the pointer ip
    // if you change the value of ip it will be
    // lost when the function ends (because it is a copy)
}

Then this:

void func2(int*& ip)
{
    // in here you have a REFERENCE to the pointer ip
    // if you change the value of ip you are really
    // changing the value of the pointer that the 
    // function was called with.
}

So now:

int main()
{
    int* ip = new int;

    // func1 can not change ip here (only its own copy)
    func1(ip); 

    // If func2 changes ip we will see the change out here
    // because it won't be a copy that changes it will be the 
    // one we passed in that gets changed.
    func2(ip); 

    // etc...
}

Hope that helps.

0
M.M On

In this code it is being used as an output parameter.

Here is a simpler example of using a reference as an output parameter:

void get_number(int &x)
{
    x = 5;
}

int main()
{
    int y;
    get_number(y);
    cout << y << '\n';   // prints 5
}

In this code, get_number has one output parameter and no input parameters or return value.

Normally you would use the return value instead of a single output parameter, but sometimes the output parameter has its advantages.