0

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;
}
takashi
  • 1
  • 1
  • 2

3 Answers3

1

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;
}

https://godbolt.org/z/nx1139

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;
}

https://godbolt.org/z/fMx8G6

0___________
  • 60,014
  • 4
  • 34
  • 74
  • OP: This code will work in the real world, but you should know that dereferencing `arr` at position 5 in `addAll` is undefined behaviour (breaks the _one-past address_ rule): https://stackoverflow.com/q/25303647/1606345 – David Ranieri Sep 24 '20 at 17:11
  • None of those. No access outside bounds and no access via subscripts out of range. – 0___________ Sep 24 '20 at 19:54
  • Yes Sir, it is quite surprising, but the range of `arr` is only valid from `arr[0]` to `arr[4]`, the rest of the elements cannot be deferenced due to the one-past rule, it is very unlikely that there will be problems, since C doesn't do range checking, but it's UB, anyway it was an observation to the OP, I was pretty sure you would deny the obvious (it is well explained in the accepted answer). – David Ranieri Sep 24 '20 at 20:13
0

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);
    }
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
0

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.

user694733
  • 15,208
  • 2
  • 42
  • 68