所以我认为C ++按值工作,除非您使用指针。
尽管今天我编写了这段代码,其工作方式与预期不同:
#include <iostream>
using namespace std;
void bubbleSort(int A[],int arrSize);
bool binarySearch(int B[],int key,int arrSize2);
int main(){
int numberArr[10] = {7,5,3,9,12,34,24,55,99,77};
bool found;
int key;
bubbleSort(numberArr,10);
/**
uncomment this piece of code
for(int i=0; i<10; i++){
cout<<numberArr[i]<<endl;
}
**/
cout<<"Give me the key: ";
cin>>key;
found=binarySearch(numberArr,key,10);
cout<<found;
}
void bubbleSort(int A[],int arrSize){
int temp;
for(int i=0; i<arrSize-1; i++){
for(int j=i+1; j<10; j++){
if(A[i]>A[j]){
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
}
}
bool binarySearch(int B[],int key,int arrSize2){
int i=0;
bool found=false;
while(i<arrSize2 && !found){
if(B[i]==key)
found=true;
i++;
}
return found;
}
运行此命令时,numberArr
中的值似乎也在main()
函数中更改(排序),只需取消注释注释的块。
关于numberArr
函数中main
的值为什么也改变的任何想法?
int[]
,array decaying作为类型基本上仍然是指针。因此,您传递的是数组“引用”(如将用于“传递引用”的值,而不是像int&
这样的实际C ++引用),而不是“值”。
int[]
或int*
本身的“值”仍然是“传递值”,只是该值正被用于通过引用访问“指向”对象的内存。
在C ++中,您不能按值传递数组。