cpointersreturnpass-by-pointer

How to print result of function in C using pointer (w/o return)


My task is to write a function which calculates sum of elements of array. which I did like so:

#include <stdio.h>
#include <stdlib.h>

int sum (int array[], int len){
    int i;
    int sum=0;
    for (i=0; i<len; i++){
    sum = sum + array[i];
    }
    return sum;
}


int main() {
    int array[] = {9, 4, 7, 8, 10, 5, 1, 6, 3, 2};
    int len = 10;
    printf ("Sum: %d\n" , sum(array, len)); 
}

Output: Sum: 55

however, now I need to do the very same thing but differently. The Sum function should take 3 arguments, third one being a Pointer, return no value and still be able to call it in the main function to print out the sum again. Any help would be appreciated.

P.S. Yes, it is part of homework.


Solution

  • The pointer will point to the integer variable that will receive the sum:

    void sum (int array[], int len, int *result)
    

    You call it from main giving a pointer to the result. I give no more; the rest is your homework.