私の教授は私たちに次のコードを与えましたが、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);
}
このことを考慮:
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...
}
それがお役に立てば幸いです。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加