lundi 26 mars 2018

Return reference

  1. My expected output of the following code is "1 -1 3 4 5 6". (arr[1]=2 should change to arr[1]=-1). When I run this code, nothing changes, and I can't understand why.

  2. What would be the difference if parameter "seek" will be received by "find" function by value and not by reference? When I declare that "seek" is a value, the program not running (0xC0000005)... but why does this happen?

Please advise...

int& find (int arr[], int size, int& seek) {

for (int i; i<size; i++) {
    if (arr[i]==seek) return arr[i];
}
return seek;
}

void print (int arr[], int size) {
for (int i=0; i<size; i++) {
    cout << arr[i] << " ";
}
cout << endl;
}



int main () {

int arr[]={1,2,3,4,5,6};
int size=6;
int seek=2;

find (arr, size, seek) = -1;

print(arr, size);


return 0;
}

Aucun commentaire:

Enregistrer un commentaire