【发布时间】:2020-04-01 04:07:55
【问题描述】:
所以我认为 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 B[]等价于int *B作为参数。 -
1. @UlrichEckhardt 这不等同。 2. 你可能想使用
std::array -
这是写完全相同的东西的两种不同方式,@Sahsahae,这几乎算作等价。证明:用相同的方式声明两个函数。如果它不同,那将是一个重载,因此有两个不同的功能。如果编译器认为它们相同,那么您会收到有关重新定义的错误。
标签: c++ pass-by-reference pass-by-value