Why does this code return "3, 5" when the array is not called by reference?

#include <iostream>


using namespace std;
int searchlist(int list[],int n,int value, int foundIndices[])
{
int index = -1;

for(int k=0;k<n;k++)
{
if (list[k]==value)
foundIndices[++index]=k;

}
return (index+1);

}
int main()
{
int tests[6] = {87,75,98,100,82,100};
int results[6] = {-1,-1,-1,-1,-1,-1};
int foundItems = searchlist(tests,6,100,results);
for (int m=0;m<foundItems;m++)
cout<<results[m]<<" ";

return 0;
}
Arrays are a bit special. What's actually being passed to the function are pointers to the first elements in the arrays.

 
int foundItems = searchlist(&tests[0], 6, 100, &results[0]);

To avoid this behaviour you could use std::array (or std::vector) instead of normal arrays.

http://en.cppreference.com/w/cpp/container/array
Last edited on
closed account (48T7M4Gy)
Array is passed by reference into the function, because a pointer is passed instead of a clone copy. If the array is modified inside the function, the modifications are applied to the caller's copy. You could declare the array parameter as const to prevent the array from being modified inside the function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

using namespace std;

int searchlist(const int list[], int n, int value, int foundIndices[]) // <--
{
	int index = -1;

	for (int k = 0; k < n; k++)
	{
		if (list[k] == value)
			foundIndices[++index] = k;
	}
	return (index + 1);

}
int main()
{
	int tests[6] = { 87,75,98,100,82,100 };
	int results[6] = { -1,-1,-1,-1,-1,-1 };
	int foundItems = searchlist(tests, 6, 100, results);

	for (int m = 0; m < foundItems; m++)
		cout << results[m] << " " << tests[ results[m] ] << endl; // <--

	return 0;
}
Last edited on
Topic archived. No new replies allowed.