0

why does this output 5? confused

int sum(int *p, int size) { int sum=0; for(int i=0; i<size; i++) { sum+=p[i]; } return sum; } int main() { int arr[4]={1,2,3,4}; int result=sum(&arr[1],2);///passing in address of arr[1] and passing in 2 to size cout<<result; }

6th Aug 2017, 7:34 PM
Chris
Chris - avatar
2 Answers
+ 2
arr = {1,2,3,4} &arr[1] = {2,3,4} you pass 2 to the function size, so only takes 2+3, it's 5
6th Aug 2017, 9:49 PM
Andrés04_ve
Andrés04_ve - avatar
+ 1
By passing the address of arr[i] you pass to the sum function the address of the array that starts at index i of arr (the array {2, 3, 4}). In other words: int arr[4] = {1, 2, 3, 4); int arr2[3] = {2, 3, 4}; int result = sum (&arr[1], 2); int result1 = sum (arr + 1, 2); int result2 = sum (&arr2[0], 2); int result3 = sum (arr2, 2); All the above "results" are the same thing; This happens because arr is the same thing as &arr[0] and arr + i is the same thing as &arr[i]. Hope this helped you!
6th Aug 2017, 8:21 PM
Stefan Radu
Stefan Radu - avatar