Search code examples
c++dynamic-memory-allocation

how does int*& variableName work ?


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

Solution

  • 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.