You are re-assigning the int* arr pointer to point to a different memory address created on the heap with new int[n] in this line:
arr = new int[n];
You can see your code working as expected here when commenting out that line, which means you are not accessing the actual numbers array.
It is also good practice to indicate the intention of your function through using const when passing parameters. E.g. if you want to safely prevent the re-assigning of the pointer inside your function, thus indicating "read-only", use this example:
// The order of const and the type int* matters here
int sum_of_even(int* const arr, int n)
/* Compiler error:
<source>: In function 'int sum_of_even(int*, int)':
<source>:5:13: error: assignment of read-only parameter 'arr'
arr = new int[n]; */
As an added note. Your function creates a memory leak, due to not freeing the new int[n] array. This is done through adding delete [] arr;
I would also propose to solve your problem in a modern cpp way through using the containers and std functions available in the stl.
For example, rather add your numbers to a std::vector container and use std::accumulate in combination with a lambda to sum your even numbers as in this example:
// Use a vector container for your data
std::vector<int> numbers{1, 2, 3, 4, 5};
// Create the sum with a combination of accumulate and a sum if even lambda
int sum = std::accumulate(numbers.begin(),
numbers.end(),
0, // Start with a sum of zero
[](int sum, int num) {
// Sum only on EVEN numbers
return num % 2 == 0 ? sum + num : sum;
});
arr = new int[n];?main. You pass it to the function and then overwrite the value of that pointer with a new array of uninitialized values. Seems like two different things. Are you trying to add up the even numbers in the array that was passed in, or are you trying to allocate memory in a function that will be visible outside that function?