int *& variableName有效吗?

时间:2015-06-10 22:52:13

标签: c++ dynamic-memory-allocation

我的教授给了我们以下代码,但我不完全理解int *&作品。我的理解是selectionSort函数传回了数组开始的内存位置的地址。

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 个答案:

答案 0 :(得分:2)

考虑一下:

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

然后:

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

现在:

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

希望有所帮助。

答案 1 :(得分:1)

在此代码中,它被用作输出参数。

以下是使用引用作为输出参数的更简单示例:

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

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

在此代码中,get_number有一个输出参数,没有输入参数或返回值。

通常你会使用返回值而不是单个输出参数,但有时输出参数有其优点。