Reputation: 1
I am trying to make function which will add up all the elements in an array, but I keep failing. Is something wrong with pointers, or something else? I would appreciate any help.
#include <stdio.h>
int element_sum(int *data)
{
int x = 0; //sum of all elements
for (int i = 0; i < 3; i++) //loop for row
{
for (int j = 0; j < 4; j++) //loop for column
{
x += &data[i][j];
printf("%d\n", x);
}
}
return x;
}
int main(void)
{
int data[3][4] = {{22, 23, 123, 192}, {43, 335, 44, 9}, {3, 93, 8, 7}};
int sum; // sum
sum = element_sum(*data); //function
printf("sum = %d\n", sum);
return 0;
}
Upvotes: 0
Views: 5521
Reputation: 41017
You can not use a pointer to int
to map a 2D array, should be:
int matrix_sum(int data[][4], int rows)
{
int x = 0; //sum of all elements
for (int i = 0; i < rows; i++) //loop for row
{
for (int j = 0; j < 4; j++) //loop for column
{
x += data[i][j];
printf("%d\n", x);
}
}
return q;
}
In other words, you need to know at least the last dimension, or you can use a 1D array to simulate it:
enum {rows = 3, cols = 4};
int arr[rows * cols];
int row, col, index;
for (row = 0; row < rows; row++)
{
for (col = 0; col < cols; col++)
{
index = cols * row + col;
arr[index] = index;
printf("[%d][%d] = %d\n", row, col, index);
}
}
Upvotes: 0
Reputation: 67574
As the arrays are continuous memory blocks you can do something like this for any number of dimensions:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
int addAll(int *arr, size_t nDim, ...)
{
va_list list;
size_t nElem = 1;
int result = 0;
va_start(list, nDim);
for(size_t dim = 0; dim < nDim; dim++)
{
nElem *= va_arg(list, int);
}
printf("Number of elelments %zu\n", nElem);
while(nElem--) result += *arr++;
return result;
}
int main(void)
{
int data[3][4] = {{31, 25, 12, 19}, {3, 35, 4, 46}, {8, 33, 11, 5}};
int sum; // sum
sum = addAll(*data, 2, 3, 4); //function
printf("sum = %d\n", sum);
return 0;
}
or for 3D
int main(void)
{
int data[][3][4] = {
{{31, 25, 12, 19}, {3, 35, 4, 46}, {8, 33, 11, 5}},
{{31, 25, 12, 19}, {3, 35, 4, 46}, {8, 33, 11, 5}},
{{31, 25, 12, 19}, {3, 35, 4, 46}, {8, 33, 11, 5}},
{{31, 25, 12, 19}, {3, 35, 4, 46}, {8, 33, 11, 5}},
{{31, 25, 12, 19}, {3, 35, 4, 46}, {8, 33, 11, 5}},
};
int sum; // sum
sum = addAll(**data, 3, 5, 3, 4); //function
printf("sum = %d\n", sum);
return 0;
}
Upvotes: 1
Reputation: 16043
Declare your array parameter as 2D array:
int matrix_sum(int rows, int cols, int data[rows][cols]) {
int x = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
x += data[i][j];
printf("%d\n", x);
}
}
return x;
}
Calling is simple:
sum = matrix_sum(3, 4, data);
Note that this might not work in some outdated compilers, as it requires that you have C compiler that supports C99 variable length arrays feature.
Upvotes: 0