# Question & Answer: I'm trying to write a simple function called `two_d_sum` that takes the sum of each element in a 2 dime…..

I’m trying to write a simple function called `two_d_sum` that takes the sum of each element in a 2 dimentional array and return the sum. But I can’t seem to pass the array itself to the function and the function definition does not treal int[][] as legal C code. Not sure why can someone look please? I can get the code to work if I cast the array as a pointer but I don’t want to do that.

#include <stdio.h>
#define COL 3

Don't use plagiarized sources. Get Your Custom Essay on
Question & Answer: I'm trying to write a simple function called `two_d_sum` that takes the sum of each element in a 2 dime…..
GET AN ESSAY WRITTEN FOR YOU FROM AS LOW AS \$13/PAGE

int two_d_sum(int, int[][]);

int main(void) {
int twod_array[][COL] = {{1,2,3},{23,44,1},{99,12,30}};
int count = 7;
printf(“The sum of all elements in the 2d array is %d”,
two_d_sum(3, twod_array));
}

int two_d_sum(int row, int arr[][COL]) {
int sum;
for(int i = 0; i < COL; i++)
for(int k = 0; k < row; k++){
sum += arr[i][k];
}
return sum;
}

Please give the thumbs up, if it is helpful for you. Thank you!!  Ask me if you have any doubt.

1st way of doing it: No need to give function definition. Just give your function before main.

#include <stdio.h>
#define COL 3

//int two_d_sum(int, int[][]);

int two_d_sum(int row, int arr[][COL]) {
int sum;
for(int i = 0; i < COL; i++)
for(int k = 0; k < row; k++){
sum += arr[i][k];
}
return sum;
}

int main(void) {
int twod_array[][COL] = {{1,2,3},{23,44,1},{99,12,30}};
int count = 7;
printf(“The sum of all elements in the 2d array is %d”, two_d_sum(3, twod_array));
}

2nd way: You need to pass atleast one index to function prototype.

#include <stdio.h>
#define COL 3

int two_d_sum(int, int[][COL]);

int main(void) {
int twod_array[][COL] = {{1,2,3},{23,44,1},{99,12,30}};
int count = 7;
printf(“The sum of all elements in the 2d array is %d”, two_d_sum(3, twod_array));
}

int two_d_sum(int row, int arr[][COL]) {
int sum;
for(int i = 0; i < COL; i++)
for(int k = 0; k < row; k++){
sum += arr[i][k];
}
return sum;
}