The function get_sum
expects a pointer to an int
for the second parameter, but you're passing an int
instead. Your compiler should have warned you about this.
As a result, the current value of array_sum
(which is indeterminate because it has not been initialized) is treated as a pointer value which your function subsequently dereferences. Dereferencing an invalid pointer (as well as reading an uninitialized value) invokes undefined behavior, which in this case causes a crash.
You need to pass the address of array_sum
to the function. This gives you a pointer to an int
which matches what the function expects so you can modify the value in the function.
get_sum(my_array, &array_sum);
Also, unrelated to this, the following inside of get_sum
is not correct:
int length = sizeof(array)-1;
The parameter array
is not actually an array but a pointer to the first element of an array. So sizeof(array)
gives you the size of a pointer. You might get away with it in this particular case because, assuming a pointer is 8 bytes on your system, length
gets set to 7 which happens to be the number of elements of the array my_array
in main
. If you added or removed elements things would suddenly break.
The proper way to handle this is to get the size of the actual array in main
and pass it to your function. So the function would look like this:
void get_sum(int array[], int* array_sum, int length)
And you call it like this:
int my_array[] = {25, 18, 6, 47, 2, 73, 100};
int len = sizeof(my_array)/sizeof(my_array[0]);
get_sum(my_array, &array_sum, len);