0

Is it possible to make a function that sums the values of an array in C? And if so, how?

Here's what I've got:

#include <stdio.h>
int sum(int a[][], int);

int main(void){
     int a[2][2]={{1,2}, {3,4}};
    printf("sum %d", sum(a,4));
    return 0;
}

int sum(int a[][], int n){
    int *p=a[0], sum=0;
    while(p){
        sum+=*p;
        p++;
    }
    return sum;
}
Noah M
  • 15
  • 3
  • Perhaps you should read [this](http://stackoverflow.com/questions/8767166/passing-2d-array-to-function), for knowing how to pass a multidimendionsal array to a function. – Salvador Medina Dec 07 '14 at 19:54
  • Can you tell us what's the problem with your solution? – honk Dec 07 '14 at 19:57

2 Answers2

0
#include <stdio.h>

int sum(int *a, int n);

int main(void){
     int a[2][2]={{1,2}, {3,4}};
    printf("sum %d", sum((int*)a, 4));
    return 0;
}

int sum(int *a, int n) {
    int *p = a, sum = 0;
    while(p != a + n) {
         sum += *p++;
    }
    return sum;
}
BLUEPIXY
  • 38,201
  • 6
  • 29
  • 68
-1

yes you can - i think this should work:

int sum(int **a, int n) {
    int *p = a[0], sum = 0;
    for(i = 0; i < n; i++) {
         sum+=*p;
         p++;
    }
    return sum;
}
Idan
  • 165
  • 4